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:张三
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
通过Java反射机制,可以通过子类对象获取子类父类的所有属性。可以使用 `Class.getDeclaredFields()` 方法来获取一个类的所有属性,包括私有属性。同时,需要使用 `Class.getSuperclass()` 方法来获取父类的Class对象,然后再获取父类属性。下面是一个示例代码: ```java import java.lang.reflect.Field; public class Parent { private int parentField; // 省略getter和setter方法 } public class Child extends Parent { private int childField; // 省略getter和setter方法 } public class Main { public static void main(String[] args) throws Exception { Child child = new Child(); child.setParentField(1); child.setChildField(2); // 获取子类属性 Field[] childFields = child.getClass().getDeclaredFields(); for (Field field : childFields) { field.setAccessible(true); System.out.println("Child field: " + field.getName() + " = " + field.get(child)); } // 获取父类属性 Field[] parentFields = child.getClass().getSuperclass().getDeclaredFields(); for (Field field : parentFields) { field.setAccessible(true); System.out.println("Parent field: " + field.getName() + " = " + field.get(child)); } } } ``` 在上述代码中,我们首先创建了一个Child对象,然后通过反射机制获取子类的所有属性父类的所有属性。注意,我们需要使用 `Field.setAccessible(true)` 方法来设置属性可访问,否则私有属性无法访问。运行上述代码,即可看到子类父类的所有属性
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值