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;
}
Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.
If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. By casting object1 to a Relatable type, it can invoke the isLargerThan method.
isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With