1. 程式人生 > >Class.newInstance與Constructor.newInstance對比

Class.newInstance與Constructor.newInstance對比

java建立物件有五種方式,這篇文介紹其中兩種,Class.newInstance與Constructor.newInstance都是通過反射建立java物件例項的,這兩種方式主要不同之處如下:

1.從呼叫的建構函式引數來說,Class.newInstance只能呼叫無參建構函式,Constructor.newInstance則無此限制,原因通過Class類的getDeclaredConstructor(Class<?>... parameterTypes)方法就可以知道

2.從呼叫的建構函式的可視性來說,Class.newInstance只能呼叫public型別的建構函式(不能呼叫內部類,會丟擲java.lang.ClassNotFoundException異常),Constructor.newInstance在某些情況下可以呼叫private型別的建構函式


try {
ClassB cls1 = (ClassB)Class.forName("cm.gm.test.ClassB").newInstance();
cls1.print();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {

Constructor<?> cs = ClassB.class.getDeclaredConstructor();//ClassB.class.getConstructor();//
cs.setAccessible(true);
ClassB cls2 = (ClassB)cs.newInstance();
cls2.print();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ClassB只有一個private型別的建構函式,Class.newInstance無法呼叫,但後者可以通過呼叫setAccessible來完成私有建構函式的呼叫。

3.從對建構函式丟擲的異常處理來說,Class.newInstance不做處理直接丟擲,Constructor.newInstance則會對建構函式丟擲的異常進行處理,統一丟擲