According to the question, Create instance of generic type in Java?
At the time of writing ,the best answer is found to be...
private static class SomeContainer<E> {
E createContents(Class<E> clazz) {
return clazz.newInstance();
}
}
But the answer works only for this SomeContainer.createContents("hello");
My condition is to put the class as an inner class in a generic class,then the code should be like this.
SomeContainer<T>.createContents(T);
That will produce compile time error. There is not any created references for T,also. Is there any way to create completly new T object inside the generic class?
Thanks in advance
Trelated to the type parameter of the enclosing generic class? It would be better if you show short version of your class.SomeContainer<T>.createContents(T.class);?Class<E>, useClass<? extends E>; this way, someone can pass in an instance of a subclass's class, or use thegetClass()method on an object (as it returnsClass<? extends |X|>where|X|is the reference type of the object) without a cast..classnotation on a generic type parameter, because of type erasure.