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();
    }

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap