Java Generics: Type parameter cannot be instantiated directly


package org.code2care.generics;

public class Example<K,V> {
    
    public void method() {
        K k = new K();
        V v = new V();
    }
}

If you are working inside a Java IDE like IntelliJ, you would see a compliation error in the above code that reads "Type parameter 'K' cannot be instantiated directly". This is because you cannot create an instance of a generic type parameter directly, it has to be a class.

To better understand this, you can refer to the official Java Generics Tutorial: Restrictions on Generics

Type parameter K cannot be instantiated directly

Fix:

One workaround would be to create an instance of an Object class which is the parent of all classes in Java and cast it to your generic type.

    public void method() {
        K k = (K) new Object();
        V v = (V) new Object();
    }
-




Have Questions? Post them here!