class Parent
{ //need to access variable of child class
}
class Child extends Parent
{ int a=10;
}
答案 0 :(得分:1)
您必须了解孩子的一些方式 - 通过设计或使用反射发现。
此示例取决于“a”是“package”或“public”而非“private”。
public int getChildA() {
int a = 0;
if (this instanceof Child) {
a = ((Child)this).a;
}
return a;
}
答案 1 :(得分:0)
如果你真的必须,你需要做的是尝试用反射获得该领域,并抓住找不到该领域的可能性。尝试类似:
static class Parent
{
public int getChildA(){
try {
Class clazz = Child.class;
Field f = clazz.getDeclaredField("a");
if(!f.isAccessible())
f.setAccessible(true);
return f.getInt(this);
} catch (NoSuchFieldException ex) {
//the parent is not an instance of the child
} catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SOtests.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
}
static class Child extends Parent
{
int a=10;
}
public static void main(String[] args) {
Child c = new Child();
Parent p = (Parent) c;
System.out.println(p.getChildA());
}
输出为10
,但从设计角度来看,这仍然是一个非常糟糕的主意。我还必须为演示制作课程,但你可以毫无问题地改回它们。