Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class object type parameterization in Java

Suppose the following object structure:

class Super {}

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

I want to be able to have a variable that will hold the class object for either of my subclasses. I feel like this should do it:

Class<Super> classObj;

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

classObj = SubA.class;

or:

classObj = SubB.class;

This doesn't work though. I get the following error:

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

Any ideas why? What do I need to fix?

like image 817
pkaeding Avatar asked Dec 08 '22 07:12

pkaeding


1 Answers

You need a bounded wildcard:

Class<? extends Super> classObj;

See the lesson on wildcards from the Java tutorials.

like image 141
Michael Myers Avatar answered Dec 24 '22 08:12

Michael Myers