Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate an object of a class where the class is given via generics [duplicate]

Tags:

java

generics

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.

like image 567
Drakekin Avatar asked Jan 29 '13 16:01

Drakekin


People also ask

Can you instantiate a generic type?

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.

How do you initialize a generic object in Java?

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.


1 Answers

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);
}
like image 189
Brian Agnew Avatar answered Nov 02 '22 10:11

Brian Agnew