Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Class.forName() with constructor arguments

 
Randy Johnson
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic