![](/img/trans.png)
[英]What is the difference between the new operator and Class.newInstance()?
[英]java object creation using new operator and .class.newInstance() method
我有以下代碼片段
public class Test2 {
public static void main(String[] args) {
Test test = null;
try {
test = Test.class.newInstance();
if(test!=null)
System.out.println("test class instance created");
System.out.println(test.getA()+"\t"+test.getB());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Test {
private int a;
private int b;
public Test() {
// TODO Auto-generated constructor stub
System.out.println("test class constructor executed");
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
static {
System.out.println("static block of Test class exectuted");
}
{
System.out.println("test class IIB executed");
}
我正在嘗試使用創建Test類的實例
test = Test.class.newInstance();
我的問題:這是正確的方法嗎?
而且之間也有什么區別
Test t1 = new Test();
和以上的方法?
當我運行Test2類時,我得到以下關注:
static block of Test class exectuted
test class IIB executed
test class constructor executed
test class instance created
0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.