Reputation: 6815
I am using JAVA7. I have below class.
public class SomeClass<B extends Base, L extends Last>{
Class<L> last;
Class<B> base;
public SomeClass(Class<L> last, Class<B> base){
this.last=last;
this.base=base;
}
}
here i need to create a method which will accept class type and create its instance and return. how can i do that?
public returnclassinstance createInstance(Class class)
I would call this method by passing either last/base. This method has to create the instance of the passed class type and return the same. Is it possible?
Thanks!
Upvotes: 1
Views: 4626
Reputation: 695
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).
Upvotes: 2