• Post Reply Bookmark Topic Watch Topic
  • New Topic

class loader  RSS feed

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can create MyObj objects in following two ways: whats the fundemental difference?

Class class = Class.forName(..)
MyObj obj1 = (MyObj) class.newInstance(..)
MyObj obj2 = new MyObj();
 
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's not a lot of difference the way you showed them, but there can be ...

With the first method, you can create a class that is not known at compile time. At run time you might get the classname as a string from any source - configuration or user entered or whatever - and make an instance. Very powerful in the right situation.

With the third method, you can call constructors with parameters, like new MyClass( size, color );

There's a fourth (more obscure) way, too: Class.getConstructor().invoke() or something like that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!