We help IT Professionals succeed at work.

Instantiating a class whose name is provided as a string

onaled777
onaled777 asked
on
Is there any way to instantiate a class from a string at runtime?

I've heard scripting languages can do it, but can java?
Comment
Watch Question

Awarded 2011
Awarded 2011
Commented:
In Java you can use Reflection for that purpose
Awarded 2011
Awarded 2011
Commented:
Awarded 2011
Awarded 2011
Commented:
Look at this piece if code:

      Class theClass  = Class.forName(aArguments[0]);
      Interpreter interpreter = (Interpreter)theClass.newInstance();
      Console console = new Console(interpreter);
      console.run();

Open in new window


make sure that you include full qualified name with package etc.
and of course the class hsould be in the classpath
Awarded 2011
Awarded 2011
Commented:
also look at this example - this one is using reflection
and in a sense it is different form Class.forName(),
as Class.forName() will requre at least to have interface explicitly
appaearing - like "Interpreter" in the example above.
With reflcetion you don't need it

http://tutorials.jenkov.com/java-reflection/constructors.html

This is one of the eacmples from the link above:
Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject)
        constructor.newInstance("constructor-arg1");

Open in new window


there are soem other examples also.

Of course, once again you need to have the class available
through the class path
Awarded 2011
Awarded 2011
Commented:
Top Expert 2016
Commented:
>>Or even Class.ForName  will work:

That IS reflection ;)