This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference b/n Class.newInstance and new

 
Vasim Patel
Ranch Hand
Posts: 87
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic