Possible Duplicate:
Create instance of generic type in Java?
I have some code:
public class foo<K> {
public void bar() {
K cheese = new K();
// stuff
}
}
This does not compile and Intellij's linter tells me Type parameter 'K' cannot be instantiated directly
.
How would I instance a new copy of K
.
Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.
If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.
You can't do this nicely due to type erasure. The standard means of doing it is to pass the appropriate Class
object, and use this to instantiate a new instance.
e.g. from here:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With