java反射最常用的几个方法

1.获取javaBean的属性

  Student s = new Student();
  Class<? extends Student> class1 = s.getClass();
  //获取public的属性
  Field[] fields = class1.getFields();
  //获取所有的属性
  Field[] declaredFields = class1.getDeclaredFields();
  for(Field f:fields) {
  System.out.println("***执行getFields()方法***");
        System.out.println(f);
  }
  for(Field f:declaredFields) {
        System.out.println("***执行getDeclaredFields()方法***");
        System.out.println(f);
  }

2.获取javaBean的方法

//获取本类及父类public的方法
Method[] methods = class1.getMethods();
for(Method m:methods) {
        System.out.println("***执行getMethods()方法");
        System.out.println(m);
}
//获取本类当中所有的方法
Method[] methods2 = class1.getDeclaredMethods();
for(Method m:methods2) {
       System.out.println("***执行getDeclaredMthods()方法***");
       System.out.println(m);
}

3.通过反射进行Bean与Bean之间的转换

/**
     * 实体类之间转换
     * @param source:源类
     * @param target:要转换的目标类
     * @return
     */
    public static Object convertBean(Object source,Object target) {
        //获取来源类的所有方法
        Method[] sourceMethods = source.getClass().getDeclaredMethods();
        //要转换目标类的所有方法
        Method[] targetMethods = target.getClass().getDeclaredMethods();
        //遍历源类的所有方法
        for(Method sm:sourceMethods) {
            //取源类的方法名称
            String sourceMethodName = sm.getName();
            //以get开头的方法
            if(sourceMethodName.startsWith("get")) {
                try {
                    Object value = sm.invoke(source);
                    for(Method tm:targetMethods) {
                        String targetMethodName = tm.getName();
                        if(targetMethodName.startsWith("set") && (sourceMethodName.substring(3, sourceMethodName.length()).equals(targetMethodName.substring(3,targetMethodName.length())))) {
                            tm.invoke(target, value);
                        }
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return target;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值