flyingfromchina
flyingfromchina

Reputation: 9691

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) {

  //return true is c is an implementation of the interface List

}

Thanks

Upvotes: 0

Views: 180

Answers (4)

Bozho
Bozho

Reputation: 597056

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.

Upvotes: 8

Bala R
Bala R

Reputation: 108947

try using the instanceof operator.

return c instanceof List;

Upvotes: 4

bmargulies
bmargulies

Reputation: 100013

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.

Upvotes: 0

Amir Raminfar
Amir Raminfar

Reputation: 34149

If it is an instance the you do

c instanceof List

if its a class then you do

List.class.isAssignableFrom(c)

Upvotes: 2

Related Questions