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 useList.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 useobj 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.
精彩评论