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?
You need a bounded wildcard:
Class<? extends Super> classObj;
See the lesson on wildcards from the Java tutorials.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With