import java.lang.reflect.Field;
class Parent {
private String parentField = "I'm a parent field";
public String getParentField() {
return parentField;
}
}
class Child extends Parent {
private String childField = "I'm a child field";
}
public class ReflectionExample {
public static void main(String[] args) {
try {
// 获取子类的Class对象
Class<?> childClass = Child.class;
// 创建子类实例
Object childInstance = childClass.getDeclaredConstructor().newInstance();
// 获取父类的Class对象
Class<?> parentClass = childClass.getSuperclass();
// 获取父类的所有属性(包括私有属性)
Field[] fields = parentClass.getDeclaredFields();
for (Field field : fields) {
// 设置访问权限为可访问(即使是private修饰的属性)
field.setAccessible(true);
// 获取属性名称和值
String fieldName = field.getName();
Object fieldValue = field.get(childInstance);
System.out.println("Parent field name: " + fieldName);
System.out.println("Parent field value: " + fieldValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
定义父类 Parent 和子类 Child:
Parent 中有一个私有属性 parentField。Child 继承自 Parent,并有自己的私有属性 childField。获取子类的 Class 对象:
Child.class 获取子类的 Class 对象。创建子类实例:
childInstance。获取父类的 Class 对象:
getSuperclass() 方法获取父类的 Class 对象。获取父类的所有属性:
getDeclaredFields() 方法获取父类的所有属性,包括私有属性。设置属性为可访问:
field.setAccessible(true) 来确保可以访问私有属性。获取属性名称和值:
field.getName() 获取属性名称。field.get(childInstance) 获取属性值。输出结果:
上一篇:java 随机
下一篇:java super()
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站