• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class.forName() when there is more than one constructor  RSS feed

 
Geoff Wass
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my first post here and I wasn't sure given the topic of my question whether it was a beginner question or intermediate. If I guessed incorrectly, my apologies...


I have a class with a default constructor (no parameters) and one constructor with one parameter. I understand how to use Class.forName() to get an instance of the class based on the default constructor:

class.forName("com.whatever.myClass")

How do I use Class to get an instance of the same class, but based on the constructor which has a parameter? (I have the parameter waiting in the wings, ready to be passed to it!)

I think it will mean using class.forName(String name, boolean initialize, ClassLoader loader), but I don't quite follow the stuff about class loaders.

Many thanks in advance for all your help.
 
Mike Fuellbrandt
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class.forName(String className) returns an object representation of the class, not an instance of that class.

The Class class (confusing, eh?) represents the actual class, with it's methods, fields and constructors.

To answer your question: Class.forName(String className) returns both instances of your object, in a way.

Check out the Class.getConstructors() method, to get all of the constructors for your class, and then check out Constructor.newInstance() method to create a new instance of the class.

Hope this helps and wasn't too confusing.

Mike Fuellbrandt (fellow Canuck)
 
Geoff Wass
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike,

Thank-you for this information. I think I follow what you are saying. I was not expecting such a fast reply. I think this will put me on the right track now. I appreciate your help.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!