随笔 - 44  文章 - 3  评论 - 4  阅读 - 94228 

说明:

  作为反射工具类,通过对象和属性的名字获取对象属性的值,如果在当前对象属性没有找到,依次向上收集所有父类的属

性,直到找到属性值,没有找到返回null;

代码:

  1.classUtil

  

复制代码
package com.example.demo.utill;

import java.lang.reflect.Field;

/**
 * description: TODO
 * date: 2020/3/24 0024 下午 21:32
 *
 * @author : Administrator
 * @since : 1.0
 **/
public class ClassUtil {

    public static Object getPropertyValue(Object obj, String propertyName) throws IllegalAccessException {
        Class<?> Clazz = obj.getClass();
        Field field;
        if ((field = getField(Clazz, propertyName)) == null)
            return null;
        field.setAccessible(true);
        return field.get(obj);
    }

    public static Field getField(Class<?> clazz, String propertyName) {
        if (clazz == null)
            return null;
        try {
            return clazz.getDeclaredField(propertyName);
        } catch (NoSuchFieldException e) {
            return getField(clazz.getSuperclass(), propertyName);
        }
    }
}
复制代码

  2.测试类和接口

复制代码
package com.example.demo.utill;

/**
 * description: TODO
 * date: 2020/3/24 0024 下午 21:50
 *
 * @author : Administrator
 * @since : 1.0
 **/
public class Person {
    private String age;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
复制代码
复制代码
package com.example.demo.utill;

/**
 * description: TODO
 * date: 2020/3/24 0024 下午 21:42
 *
 * @author : Administrator
 * @since : 1.0
 **/
public class User  extends Person{
    private String name ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
复制代码

3.测试

复制代码
package com.example.demo.utill;

/**
 * description: TODO
 * date: 2020/3/24 0024 下午 21:41
 *
 * @author : Administrator
 * @since : 1.0
 **/
public class Test {
    public static void main(String[] args) throws IllegalAccessException {
        User u = new User();
        u.setName("张三");
        u.setAge("20");
        Object o = ClassUtil.getPropertyValue(u,"ag1e");
        System.out.println(o);
    }
}
// outPut:null
复制代码

 

posted on   JonRain0625  阅读(12460)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示