To create new instance based on java Class
type, you should use something like this:
public <T> T createInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
Note that T
should have public default constructor. If you want to use other that default construtors to create new instance of Class
, then you should look into reflection (e.g. clazz.getDeclaredConstructors()
).
EDIT: using constructor with arguments
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public Test(String arg) {
System.err.println("I'm in consturctor with one String arg: " + arg);
}
public static <T extends Test> T createInstance(Class<T> clazz) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor<T>[] constructors = (Constructor<T>[]) clazz.getDeclaredConstructors();
Constructor<T> constructor = constructors[0];
return constructor.newInstance("ARG");
}
public static void main(String[] args) throws Exception {
createInstance(Test.class);
}
}
After running this code you should get on output:
I'm in consturctor with one String arg: ARG
But note how ugly this code is - using reflections in Java for such object creation is in my opinion the last option (if we don't have any other solutions).