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;
}