Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no
(due to type erasure), but
Hope this's not too late to help!!!
Java is type-safe, meaning that only Objects are able to create instances.
In my case I cannot pass parameters to the createContents
method. My solution is using extends unlike the answer below.
private static class SomeContainer {
E e;
E createContents() throws Exception{
return (E) e.getClass().getDeclaredConstructor().newInstance();
}
}
This is my example case in which I can't pass parameters.
public class SomeContainer {
E object;
void resetObject throws Exception{
object = (E) object.getClass().getDeclaredConstructor().newInstance();
}
}
Using reflection create run time error, if you extends your generic class with none object type. To extends your generic type to object convert this error to compile time error.