wood burning stoves 2.0*
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
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
Author

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.class.newInstance();
vs
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
    
    1
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).

Geoffrey


Sun Certified Programmer for the Java 2 Platform
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: difference b/n Class.newInstance and new