-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