方法介绍
1.获取所有属性
private static List<Field> getAllField(Class<?> class1){
List<Field> list=Lists.newArrayList();
while (class1!= Object.class){
list.addAll(Arrays.stream(class1.getDeclaredFields()).collect(Collectors.toList()));
class1=class1.getSuperclass();
}
return list;
}
2.获取属性值的方法
public Object get(Object obj)
throws IllegalArgumentException, IllegalAccessException
父类使用
父类定义
@Data
@AllArgsConstructor
@NoArgsConstructor
class Parent{
private Integer parentId;
private String parentName;
}
获取父类属性值
public static void main(String[] args) {
List<Parent> parentList= Lists.newArrayList();
Parent parent=new Parent(1,"张三");
parentList.add(parent);
parent=new Parent(2,"张三");
parentList.add(parent);
List<Field> list1 =getAllField(Parent.class);
parentList.forEach(parent1 -> {
list1.forEach(field -> {
field.setAccessible(true);
try {
String fieldName = field.getName();
Object fieldValue = field.get(parent1);
System.out.println(fieldName+":"+fieldValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
});
}
结果打印
parentId:1
parentName:张三
parentId:2
parentName:张三
子类使用
子类定义
@Data
@EqualsAndHashCode(callSuper = true)
class Son extends Parent{
private Integer sonId;
private String sonName;
public Son(Integer parentId, String parentName, Integer sonId, String sonName) {
super(parentId, parentName);
this.sonId = sonId;
this.sonName = sonName;
}
}
获取子类属性值
public static void main(String[] args) {
List<Son> sonList=Lists.newArrayList();
Son son=new Son(1,"张三",11,"张三儿子1");
sonList.add(son);
son=new Son(2,"张三",12,"张三儿子2");
sonList.add(son);
List<Field> list2 = getAllField(Son.class);
sonList.forEach(son1 -> {
list2.forEach(field -> {
field.setAccessible(true);
try {
String fieldName = field.getName();
Object fieldValue = field.get(son1);
System.out.println(fieldName+":"+fieldValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
});
}
结果打印
sonId:11
sonName:张三儿子1
parentId:1
parentName:张三
sonId:12
sonName:张三儿子2
parentId:2
parentName:张三
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)