开发者

test for subclass with getType in conditional in java

开发者 https://www.devze.com 2023-02-05 19:07 出处:网络
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 th

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 actual开发者_StackOverflowly 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号