1

I'm trying to check if an object implements an interface (If that class of that object implements the interface) in Java.

How do I do that?

I saw you can do this.getClass().getInterfaces(), but that gives me an array, and I need to search that array, but what do I use to check?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2338361
  • 79
  • 2
  • 2
  • 6
  • 3
    When you were asking your question, just typing in your title, the SO interface showed you a list of existing questions related to it. [The question assylias, myself, and others](http://stackoverflow.com/questions/766106/test-if-object-implements-interface) pointed to above was **number two on that list**. Why bother to ask the question again when the answer is already there? – T.J. Crowder May 16 '13 at 11:25
  • The question does not deserve being downvoted so much... – assylias May 16 '13 at 11:25
  • 1
    @assylias: Some people interpret "...does not show research effort..." as including not bothering to look at the list of similar questions when they were asking. (For good or ill...) – T.J. Crowder May 16 '13 at 11:26
  • I guess OP wants to know that either a class has implement a interface or not.Like if he is using a class A from any API then he wants to know that if A has implemented any interface. For OP -> you should study the Docs for that purpose – Freak May 16 '13 at 11:27
  • 1
    @T.J.Crowder Yes I know but for a new user it is not necessarily obvious - your comment is more useful than serial downvoting. – assylias May 16 '13 at 11:28

2 Answers2

5

If you need to know if instance foo is of a class implementing a given interface, you can use instanceof:

if (foo instanceof TheInterface)
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

You can use the instanceof operator in Java. JLS says,

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException.

instanceof operator is a binary operator used to test if an object (instance) is a sub type of a given type.

// checks if bar object's class implements SomeInterface
if (bar instanceof SomeInterface)
AllTooSir
  • 48,828
  • 16
  • 130
  • 164