Mar*_*ark 2 java inheritance constructor static-typing java-8
我在类构造函数中的反射与继承一起使用时遇到问题。具体来说,我想获取所有属性值。
这是一个简单实现的演示,但不起作用:
import java.lang.reflect.Field;
public class SubInitProblem {
public static void main(String[] args) throws IllegalAccessException {
Child p = new Child();
}
}
class Parent {
public int parentVar = 888888;
public Parent() throws IllegalAccessException {
this.showFields();
}
public void showFields() throws IllegalAccessException {
for (Field f : this.getClass().getFields()) {
System.out.println(f + ": " + f.get(this));
}
}
}
class Child extends Parent {
public int childVar = 999999;
public Child() throws IllegalAccessException {
super();
}
}
Run Code Online (Sandbox Code Playgroud)
这将显示childVar为零:
public int Child.childVar: 0
public int Parent.parentVar: 888888
Run Code Online (Sandbox Code Playgroud)
因为还没有初始化。
所以我想我不需要直接使用构造函数,而是让构造函数完成然后使用showFields:
import java.lang.reflect.Field;
public class SubInitSolution {
public static void main(String[] args) throws IllegalAccessException {
SolChild p = SolChild.make();
}
}
class SolParent {
public int parentVar = 888888;
protected SolParent() {
}
public static <T extends SolParent> T make() throws IllegalAccessException {
SolParent inst = new SolParent();
inst.showFields();
return (T) inst;
}
public void showFields() throws IllegalAccessException {
for (Field f : this.getClass().getFields()) {
System.out.println(f + ": " + f.get(this));
}
}
}
class SolChild extends SolParent {
public int childVar = 999999;
public SolChild() throws IllegalAccessException {
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为make不能返回子类的正确类型。(所以问题是new SolParent();)。
解决这个问题的最佳方法是什么?我需要所有子类来执行showFields,但我不能依赖它们显式地执行它。
您的 showFields 方法需要遍历类层次结构,如下所示:
public void showFields() throws IllegalAccessException {
Class<?> clz = this.getClass();
while(clz != Object.class) {
for (Field f : clz.getDeclaredFields()) {
f.setAccessible(true);
System.out.println(f + ": " + f.get(this));
}
clz=clz.getSuperclass();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用了Class.getDeclaredFields(),而不是Class.getFields(),因为后者仅处理公共字段。
这就是如何以通用方式构建类的方法:
public static <T extends SolParent> T make(Class<T> type) throws Exception {
Constructor<T> constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
T inst = constructor.newInstance();
inst.showFields();
return inst;
}
Run Code Online (Sandbox Code Playgroud)
SolParent请注意,只有当您的子类型具有公共无参数构造函数(或根本没有构造函数)时,这才有效。
| 归档时间: |
|
| 查看次数: |
1393 次 |
| 最近记录: |