Test for subclass with getType in conditional expression in java

I need to find out if the type of the returned method is a subclass of a specific base class. Until I can find a built-in way to do this, I can find a way to check if the class matches exactly. I can also do this with annotations, but the idea is that I don't want to add extra code if I manage to add a new subclass. I was thinking of testing all possible subclasses or creating an untyped object and testing its instance with "instanceof", but nothing seems perfect. Perfectly:

if (m.getReturnType() Extends Superclass.class)

but there are no "extensions" with functionality similar to "instanceof" with actual instances. Is there a conditional statement that I don't know about? Thank you in advance for any ideas.

This is valid for the Android project, so I can not realize all the features.

+3
source share
1 answer

I think you want to use Class.isAssignableFrom(Class).

When using it only with regular Java,

   System.out.println(List.class.isAssignableFrom(LinkedList.class));

Prints out true. How does it do:

  System.out.println(Queue.class.isAssignableFrom(LinkedList.class));

Because LinkedList can be considered both List and Queue. Nonetheless,

   System.out.println(ArrayList.class.isAssignableFrom(LinkedList.class));

Printing false, since LinkedList cannot be treated as an ArrayList.

+5
source

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


All Articles