tags:

views:

2409

answers:

5

This has probably been asked before, but a quick search only brought up the same question asked for C#. See here.

What I basically want to do is to check wether a given object implements a given interface.

I kind of figured out a solution but this is just not comfortable enough to use it frequently in if or case statements and I was wondering wether Java does not have built-in solution.

public static Boolean implementsInterface(Object object, Class interf){
    for (Class c : object.getClass().getInterfaces()) {
        if (c.equals(interf)) {
            return true;
        }
    }
    return false;
}


EDIT: Ok, thanks for your answers. Especially to Damien Pollet and Noldorin, you made me rethink my design so I don't test for interfaces anymore.

+4  A: 

This should do:

public static boolean implementsInterface(Object object, Class interf){
    return interf.isInstance(object);
}

For example,

 java.io.Serializable.class.isInstance("a test string")

evaluates to true.

Pourquoi Litytestdata
+2  A: 

that was easy :

   interf.isInstance(object)
Andreas Petersson
beaten by 30 secs :(
Andreas Petersson
+1  A: 

Testing for the type of an object typically brings bad OO karma! So what's your actual goal?

Damien Pollet
+7  A: 

also the instanceof operator does the work, in a NPE safe way. For example:

 if ("" instanceof java.io.Serializable) {
     // it's true
 }

yields true. Since:

 if (null instanceof AnyType) {
     // never reached
 }

yields false, the instanceof operator is null safe (the code you posted isn't).

instanceof is the built-in, compile-time safe alternative to Class#isInstance(Object)

dfa
instanceof only works on class literals though. So it can't be used in the OP's case
LordOfThePigs
sure, it is compile-time safe; and it is the built-in way and it is the argument of the question (imho)
dfa
+1  A: 

I prefer instanceof:

if (obj instanceof SomeType) { ... }

which is much more common and readable than SomeType.isInstance(obj)

Steve Kuo