簡體   English   中英

使用new運算符和.class.newInstance()方法創建Java對象

[英]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

這是正確的方法嗎?

不它不是。 使用new 因為Class.newInstance()

這種方法的使用有效地繞過了編譯時異常檢查,否則該檢查將由編譯器執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM