Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to instantiate a class from string [duplicate]

Possible Duplicate:
Create new class from a Variable in Java

I have a string

String className = "DummyClass" 

Now I want to create a class object where the class name is className That is something like

Object className = new className() // I know it's not possible. 

I want to know how to do this...

like image 651
Dewsworld Avatar asked Sep 21 '11 07:09

Dewsworld


People also ask

How do you instantiate a class dynamically in Java?

If your class has a no-arg constructor, you can get a Class object using Class. forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

How do you initiate a class in Java?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.


2 Answers

"Using java.lang.reflect" will answer all your questions. First fetch the Class object using Class.forName(), and then:

If I want to instantiate a class that I retrieved with forName(), I have to first ask it for a java.lang.reflect.Constructor object representing the constructor I want, and then ask that Constructor to make a new object. The method getConstructor(Class[] parameterTypes) in Class will retrieve a Constructor; I can then use that Constructor by calling its method newInstance(Object[] parameters):

Class myClass = Class.forName("MyClass");  Class[] types = {Double.TYPE, this.getClass()}; Constructor constructor = myClass.getConstructor(types);  Object[] parameters = {new Double(0), this}; Object instanceOfMyClass = constructor.newInstance(parameters); 

There is a newInstance() method on Class that might seem to do what you want. Do not use it. It silently converts checked exceptions to unchecked exceptions.

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

like image 60
Mike Samuel Avatar answered Sep 16 '22 19:09

Mike Samuel


You can use reflection. For example,

Object o = Class.forName(className).newInstance();  

But className should contain full path to the class.

like image 34
Ilmirus Avatar answered Sep 20 '22 19:09

Ilmirus