我不能創建B對象,但爲什麼?使用反射實例化內部類時的InstantiationException。爲什麼?
public class AFactory {
public int currentRange;
private abstract class A {
protected final Object range = currentRange;
public int congreteRange = 28;
}
public class B extends A {
public int congreteRange = 42;
}
synchronized A createNew(Class<? extends A> clazz) throws Exception {
// EDIT: there is accessible default constructor
currentRange = clazz.newInstance().congreteRange;
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
AFactory factory = new AFactory();
System.out.println(factory.createNew(B.class).range);
}
}
的例外是:
Exception in thread "main" java.lang.InstantiationException: AFactory$B
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:325)
at AFactory.createNew(AFactory.java:15)
at AFactory.main(AFactory.java:21)
但是我已經有了一個外部類'new AFactory()'的實例! –
@SotiriosDelimanolis。這是現在的靜態領域。我改變了它。 –
@Rohit Jain - 你確定嗎?我認爲可以創建一個內部類的實例。它是公共的,它有一個要附加到的'AFactory'()實例。 – Avi