开发者

How to determine if a class which is an implemenation of an interface in java

开发者 https://www.devze.com 2023-03-06 17:06 出处:网络
I need to write a function to return true if the incoming java Class is an implementation of the interface List. Does anybody know how to do this in java?

I need to write a function to return true if the incoming java Class is an implementation of the interface List. Does anybody know how to do this in java?

something like:

public boolean canConvert(Class c) {

  //r开发者_开发技巧eturn true is c is an implementation of the interface List

}

Thanks


There are two distinct scenarios:

  • you want to check if a given class is a subclass/implementor of List. Judging from your method signature (Class c), this is what you want. In that case use

    List.class.isAssignableFrom(c)
    
  • you want to see if a given object is an instance of a class that us a subclass/implementor of List. In that case use obj instanceof List, as Bala R suggested.


try using the instanceof operator.

return c instanceof List;


If it is an instance the you do

c instanceof List

if its a class then you do

List.class.isAssignableFrom(c)


By calling this function of Class which answers the question fairly broadly. If you need to specifically know if it directly implements, you have to walk the data structures.

A more specific answer comes from searching the results of getInterfaces.

0

精彩评论

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