Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes 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