开发者

How to determine if a class which is an implemenation of an interface 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜