说明:

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

性,直到找到属性值,没有找到返回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 2020-03-24 22:09  JonRain0625  阅读(12439)  评论(0编辑  收藏  举报