-4
class Parent
{ //need to access variable of child class
}
class Child extends Parent
{ int a=10;
}
class Parent
{ //need to access variable of child class
}
class Child extends Parent
{ int a=10;
}
您将不得不通过设计或使用反射发现来了解孩子的一些情况。
此示例取决于“a”是“包”还是“公共”而不是“私人”。
public int getChildA() {
int a = 0;
if (this instanceof Child) {
a = ((Child)this).a;
}
return a;
}
如果您确实需要做的是,您需要做的就是尝试使用反射来获得该字段并捕获该字段未找到的可能性。尝试是这样的:
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
,但是这仍然是从前瞻性设计一个非常糟糕的主意。我还必须为演示制作课程,但您可以将其更改为无问题。
没有。如果没有大量的反思,而且通常是一个坏主意,这是不可能的。 – Dallen
父母不应该有任何依赖,甚至没有儿童班的知识。期。 –
这清楚地表明您的设计是错误的。 – bradimus