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
Due to implementation of generics in Java you must pass the Class<T>
object for the further use.
Here is the example:
public class Outer<E> {
private static class Inner<E> {
E createContents(Class<E> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
return null;
}
}
}
private Class<E> clazz;
private Inner<E> inner;
public Outer(Class<E> clazz) {
this.clazz = clazz;
this.inner = new Inner<>();
}
public void doSomething() {
E object = inner.createContents(clazz);
System.out.println(object);
}
}
Also you can use <? extends E>
<? extends E>
, proposed by @gparyani here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.