Test if object implements interface

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.


The instanceof operator does the work in a NullPointerException 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)


I prefer instanceof:

if (obj instanceof SomeType) { ... }

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