Class object type parameterization in Java

Assume the following structure of an object:

class Super {} class SubA extends Super {} class SubB extends Super {} 

I want to have a variable that will hold a class object for any of my subclasses. I feel this should do it:

 Class<Super> classObj; 

Then I want to be able to do something like this:

 classObj = SubA.class; 

or

 classObj = SubB.class; 

This does not work. I get the following error:

 Type mismatch: cannot convert from Class<SubA> to Class<Super> 

Any ideas why? What do I need to fix?

+4
source share
3 answers

You need a limited template:

 Class<? extends Super> classObj; 

See the wildcards lesson from the Java tutorials.

+13
source

As the miners pointed out, you can use wildcards.

Alternatively, you could implement classes with a common interface, and then access them through that interface.

+1
source

Try (do not compile):

 public class ListCopy { public static void main(String[] args) { List<String> stringList = new ArrayList<String>(); List<Object> objectList = stringList; } } 

This does not compile, although String extends Object. Java stuff is not covariant - type parameters are erased, so the compiler does not know what will be there at runtime.

Same thing with class.

+1
source

Source: https://habr.com/ru/post/1286646/


All Articles