Java高级编程十五: 反射的基本使用

203 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

第十五章 java反射机制

1.Java反射机制概述

  • 反射被视为**动态语言**的的关键,反射机制允许程序在执行期间借助于 Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性和方法
  • 加载完类之后,在堆内存的方法去产生了一个Class 类型的对象,这个对象包含了完整的类的结构信息。可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,称之为反射
graph LR
z[正常方式] --> yr
yr[引入需要的包类名称] --> n[通过new实例化]
n --> q[取得实例化对象]
fs[反射方式] --> sl[实例化对象]
sl --> gs[getClass方法]
gs --> d[阁道完整的包类名称]

  • 使用反射获取参数的值
package com.demo.common;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author eleven
 * @date 2021/3/20-14:31
 * @apiNote 一对多分页工具类
 */
public class PageUtil<T> {
    public PageParam<T> getPage(T t, List<T> data) {
        PageParam<T> page = new PageParam<>();
        Class<?> clazz = t.getClass();
        Integer currentPage = 1;
        Integer pageSize = 10;
        Integer fromIndex = 0;
        Integer toIndex = 10;
        try {
            //获取类中currentPage属性
            PropertyDescriptor currentPageMethod = new PropertyDescriptor("currentPage", clazz);
            //获取getCurrentPage()方法
            Method getCurrentPage = currentPageMethod.getReadMethod();
            //获取set方法
            Method writeMethod = currentPageMethod.getWriteMethod();
            //执行getCurrentPage()方法
            currentPage = (Integer) getCurrentPage.invoke(t);

            PropertyDescriptor pageSizeMethod = new PropertyDescriptor("pageSize", clazz);
            Method getPageSize = pageSizeMethod.getReadMethod();
            pageSize = (Integer) getPageSize.invoke(t);

        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        int from = (currentPage  - 1) * pageSize ;
        fromIndex = from > data.size() ? data.size() : from;
        toIndex = (fromIndex + pageSize) > data.size() ? data.size() : (fromIndex + pageSize);
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        Long total = (long)data.size();
        page.setTotal(total);
        page.setData(data.subList(fromIndex, toIndex));
        return page;
    }
}