I have to find out if a method return type is a subclass of a certain base class. So far I can find no built in way to do this, I can only find a way to test for an exact class match. I can also do this using annotations, but the idea is that I don't want to have to add extra code if I happen to add a new subclass. I thought of testing against all possible subclasses, or creating an untyped object and testing the instance of it using "instanceof", but nothing seems ideal. Ideally:
if (m.getReturnType() Extends Superclass.class)
but there is no "extends" with functionality similar to "instanceof" with actual instances. Is there a conditional operator that I don't know about? Thank you in advance for any ideas.
This is actually for an android project, so I might not be able to implement all possibilities.
I think you want to use Class.isAssignableFrom(Class).
When using it with just regular Java,
System.out.println(List.class.isAssignableFrom(LinkedList.class));
Prints out true. As does:
System.out.println(Queue.class.isAssignableFrom(LinkedList.class));
Because LinkedList can be treated as both a List and a Queue. However,
System.out.println(ArrayList.class.isAssignableFrom(LinkedList.class));
Prints false, since LinkedList cannot be treated like an ArrayList.
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