java反射之获取泛型对象的所有字段与对应的值(包括⽗类的)上代码:
public static void main(String[] args) throws IntrospectionException {
SysUser obj = new SysUser();
obj.setId(1L);
obj.setUserName("测试");
obj.w());
Class<?> clazz = SysUser.class;
Field[] tableFields = DeclaredFields();
Class<?> superClazz = Superclass();
if (superClazz.equals(Object.class)) {
System.out.println("没有⽗类");
} else {
Field[] tableSuperFields = DeclaredFields();
java反射的作用及应用场景Field[] superFields = new Field[tableFields.length + tableSuperFields.length];
System.arraycopy(tableFields, 0, superFields, 0, tableFields.length);
System.arraycopy(tableSuperFields, 0, superFields, tableFields.length, tableSuperFields.length);
Field[] allFields = getSuperClassFields(superFields, superClazz);
for (int i = 0; i < allFields.length; i++) {
PropertyDescriptor pd = new PropertyDescriptor(allFields[i].getName(), clazz);
Method getMethod = pd.getReadMethod();//获得get⽅法
Object fieldValue = ReflectionUtils.invokeMethod(getMethod, obj);
if(fieldValue == null){
continue;
}
System.out.println(allFields[i].getName() + "的值:" +  String());
}
}
}
//获取⽗类的所有字段
private static Field[] getSuperClassFields(Field[] tableFields, Class<?> clazz) {
Class<?> superClazz = Superclass();
if (superClazz.equals(Object.class)) {
return tableFields;
}
Field[] tableSuperFields = DeclaredFields();
Field[] c = new Field[tableFields.length + tableSuperFields.length];
System.arraycopy(tableFields, 0, c, 0, tableFields.length);
System.arraycopy(tableSuperFields, 0, c, tableFields.length, tableSuperFields.length);
getSuperClassFields(c, superClazz);
return c;
}
输出结果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。