jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes difference b/n Class.newInstance and new Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "difference b/n Class.newInstance and new" Watch "difference b/n Class.newInstance and new" New topic

difference b/n Class.newInstance and new

Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87
Is there any advantage calling newInstance over new()

Test test = new Test()
Javadoc for newInstance says

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

I see no difference
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
If you know the class beforehand, which you do in your case, just use the constructor. The newInstance() method is meant for cases when you need to use reflection to instantiate something...

James Carman, President<br />Carman Consulting, Inc.
Geoffrey Falk
Ranch Hand

Joined: Aug 17, 2001
Posts: 171
You can use clazz.newInstance() if the class has a no-argument accessible constructor. Otherwise you have to get the java.lang.reflect.Constructor and then invoke constructor.newInstance(Object[] newargs).


Sun Certified Programmer for the Java 2 Platform
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: difference b/n Class.newInstance and new
Similar Threads
difference between new and Class.forName().newInstance()
Let's say that this question is about instantiation
insert statement is not working
why this is used in synchronized block in singleton