File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
I agree. Here's the link:
subject: difference b/n Class.newInstance and new
It's not a secret anymore!