• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class instantiation : Class.forName().newInstance() vs new  RSS feed

 
Persian Sama
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I need to know on wich cases we should use the Class.forName().newInstance() procedure instead of the old new ?
Thanks
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. Welcome to the Ranch!

The only time I'd use that is if I didn't know at compile time what class I was instantiating. Let's say that you needed to create an instance of a class that was specified in a config file, so you had a String variable containing the name of the class.

You can't go:
because that won't compile - new needs to be used with the actual name of the class, not a variable. So it would be looking for a class called className, which doesn't exist. So in this case you'd have to use the other way. But new is much clearer whenever you can use it.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again Agree with MB. You need the fully‑qualified name of the class, and it only works if it has an accessible no‑arguments constructor.That will work as long as you can cast a whatever to Foo. Note the newInstance method declares several checked Exceptions which you need to handle.

As an alternative: create a factory class. In the factory class use a Map to determine which method to call, or even a switch (Java7+ only).Bar Baz and Buzz must here be subclasses of Foo. Note there is no requirement for a no‑arguments constructor.
 
Persian Sama
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew, the example you gave, make me understand the difference
 
Persian Sama
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys ;)
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first example I gave may need the cast written in the code. I can't remember.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it will need a cast. You can check whether the cast will work ahead of time though.

 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. Another bit of useful info from you
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!