This week's book giveaway is in the Game Development forum.
We're giving away four copies of Badass: Making Users Awesome and have Kathy Sierra on-line!
See this thread for details.
The moose likes Java in General and the fly likes Using Class.forName() with constructor arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Badass: Making Users Awesome this week in the Game Development forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using Class.forName() with constructor arguments" Watch "Using Class.forName() with constructor arguments" New topic

Using Class.forName() with constructor arguments

Randy Johnson

Joined: Apr 17, 2002
Posts: 22
Is there a way to use the Class.forName() method to instantiate an object with a constructor signature that includes arguments? I know the javadocs indicate that a no-arg constructor must be supplied, but was hoping someone came up with an ingenious way to make it work.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24189

Class.forName() load a class; I think you're thinking of Class.newInstance() which creates an instance of that class.

But the answer to your question is absolutely "yes". You can call the "getConstructors" method of the Class object returned from Class.forName() to get a list of java.lang.reflect.Constructor objects. This class has a newInstance() method that lets you pass arguments to the constructor.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Using Class.forName() with constructor arguments