VSK
VSK

Reputation: 250

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

Upvotes: 0

Views: 75

Answers (1)

user5547025
user5547025

Reputation:

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.

Upvotes: 1

Related Questions