1

I'm trying to create a map like this

Map<String, Class<abstractClass>> map = HashMap<String, Class<abstractClass>>();

For its input, I tried

map.put("exampleString", childClass.class);

But this doesn't work, the IDE says wrong 2nd argument type.

Found: java.lang.Class<childClass>, required java.lang.Class<abstractClass>

Even though there's an inheritance relationship between them. Does anyone know how to solve this problem?

Thanks in advance!

Cheryl
  • 39
  • 8

4 Answers4

1

You need a generic wildcard:

Class<? extends abstractClass>

This is because generic parameters by default are invariant. You could only put abstractClass.class in the map before the change.

By adding <? extends abstractClass>, you are making the generic parameter contravariant. In other situations, you can change extends to super to achieve covariance. There is an acronym for remembering when to use extends and when to use super, called PECS.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

It looks to me that the childClass.class does not extend / implement the abstract class.

Please show the childClass signature.

Ilan Keshet
  • 514
  • 5
  • 19
0

Are you sure you don't just want:

Map<String, abstractClass> map = HashMap<String, abstractClass>();
map.put("exampleString", childClass);

?

What you have is you are taking the actual meta signature of the class and putting it into a map, instead of the actual reference to a class

Ilan Keshet
  • 514
  • 5
  • 19
0

Actually I solved this problem by changing

Class<abstractClass> 

into

Class<? extends abstractClass>
Cheryl
  • 39
  • 8