說明: 作為反射工具類,通過對象和屬性的名字獲取對象屬性的值,如果在當前對象屬性沒有找到,依次向上收集所有父類的屬 性,直到找到屬性值,沒有找到返回null; 代碼: 1.classUtil package com.example.demo.utill; import java.lang.refle ...
說明:
作為反射工具類,通過對象和屬性的名字獲取對象屬性的值,如果在當前對象屬性沒有找到,依次向上收集所有父類的屬
性,直到找到屬性值,沒有找到返回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