0

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
3
  • Where did you read about Test.class.newInstance(); ? Plus, is the output what you expect? Commented Mar 16, 2016 at 15:04
  • @LutzHorn, I was just trying to instantiate Test class object using above statement, Also when I use new operator also, I got the same output. Commented Mar 16, 2016 at 16:50
  • @LutzHorn, By using Test.class.newInstance(), I can see Test class has been loaded,static and instance initializer blocks are called followed by Test class constructor. Also, same in case of new operator. Commented Mar 16, 2016 at 17:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.