Didier L
Didier L

Reputation: 20579

How to properly load a class which implements a parameterized interface?

Class<List>, Class<List<?>> or Class<List<Anything> actually refer to the same Class.

However if I have

class MyClass implements List<SomeClass> {
    // ...
}

I could then write

Class<? extends List<SomeClass>> myClass = MyClass.class;

which would then allow me to write

List<SomeClass> myInstance = myClass.newInstance();

The trick is that I would like to load this class by reflection using ClassLoader.loadClass and still declare myClass with the same type. What is the proper/simplest way to do this?

I would like a solution which does not raise compilation warnings and does not require @SuppressWarnings (which probably means to have a runtime check of the super type, like a more powerful version of Class.asSubclass).

Upvotes: 2

Views: 139

Answers (2)

Denis Tulskiy
Denis Tulskiy

Reputation: 19177

When you compile a class with generic signature, all the information about generics is lost. For jvm, it just as good as:

class MyClass implements List {
    // ...
}

You can check this if you decompile a class with javap: you'll see no generic stuff there. Generics are mostly used for compile time checks. So when you load a class with reflection, you'll have to cast it to your generic version.

Upvotes: 0

Amit Deshpande
Amit Deshpande

Reputation: 19185

 public Class<?> loadClass(String name) throws ClassNotFoundException

As It returns Class<?> Generic class, your type information is lost here. So You will have to typecast to desired type.

Upvotes: 2

Related Questions