8

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.

Community
  • 1
  • 1
Drakekin
  • 1,341
  • 1
  • 11
  • 23

1 Answers1

7

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);
}
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    I know it's just an example, but note that you could make `cls` a `Class extends E>` to demonstrate [PECS](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs). – Paul Bellora Jan 29 '13 at 16:36
  • Thanks, but you forgot to add a method invocation: List ls = new ArrayList<>(); append(ls, String.class); Even in this case I still cannot compile it. – CoolMind Jul 15 '16 at 07:54
  • See http://stackoverflow.com/a/2434182/2914140, for example. It requires one new parameter in constructor. – CoolMind Jul 15 '16 at 09:03