This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference b/n Class.newInstance and new

 
Vasim Patel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...

 
Geoffrey Falk
Ranch Hand
Posts: 171
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic