java反射获取子类或者父类的属性值

方法介绍

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:张三

你可能感兴趣的:(反射,java,jvm,开发语言)