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

第十五章 java反射机制

1.Java反射机制概述

  • 反射被视为**动态语言**的的关键,反射机制允许程序在执行期间借助于 Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性和方法
  • 加载完类之后,在堆内存的方法去产生了一个Class 类型的对象,这个对象包含了完整的类的结构信息。可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,称之为反射
正常方式
引入需要的包类名称
通过new实例化
取得实例化对象
反射方式
实例化对象
getClass方法
阁道完整的包类名称
  • 使用反射获取参数的值
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值