File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion 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: 24199

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
It's not a secret anymore!