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

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();
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!