简体   繁体   中英

java object creation using new operator and .class.newInstance() method

I have following code snippet

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");
    }

I am trying to create an instance of Test class using

test = Test.class.newInstance(); 

My Question: is this the correct way to do??

and also is there any difference between

Test t1 = new Test();

and above approach?

I am getting following as when I run Test2 Class:

static block of Test class exectuted
test class IIB executed
test class constructor executed
test class instance created
0   0

is this the correct way to do??

No, it is not. use new . Because Class.newInstance() :

Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM