java通过反射获取嵌套类对象的属性字段

 

import lombok.Data;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ReflectionTest {

    public static void main(String[] args) {

        Student student = new Student();
        student.setStudentName("学生姓名-王xx");
        Teacher teacher = new Teacher();
        teacher.setStudent(student);

        Map<String, Field> fieldMap = getFieldMap(teacher);

        Field studentField = fieldMap.get("student");

        Object studentObj = getValueByFiled(teacher, studentField);
        Map<String, Field> studentMap = getFieldMap(studentObj);

        Object studentName = getValueByFiled(studentObj, studentMap.get("studentName"));
        System.out.println("Teacher对象里的student属性对象里的studentName属性对应的value: " + studentName);
    }

    public static Object getValueByFiled(Object obj, Field field) {
        if (obj == null || field == null) {
            return null;
        }

        try {
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Map<String, Field> getFieldMap(Object obj) {
        if (obj == null) {
            return Collections.EMPTY_MAP;
        }

        Field[] fields = obj.getClass().getDeclaredFields();
        Map<String, Field> fieldObjectMap = new HashMap<>();
        for (Field field : fields) {
            fieldObjectMap.put(field.getName(), field);
        }

        return fieldObjectMap;
    }
}

@Data
class Student {

    private String studentName;
}

@Data
class Teacher {

    private String teacherName;
    private Student student;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值