I would like to check if a class implements all the methods of a specific interface without directly implementing it.
i.e. Consider the interface
public interface MyInterface {
public String myMethod();
}
and the following classes:
A implements the interface, so has the method myMethod
public class A implements MyInterface {
public String myMethod() {
return "something";
}
}
B doesn't implement the interface, but has the method myMethod
public class B {
public String myMethod() {
return "something else";
}
}
So MyInterface.class.isAssignableFrom(A.class); is true and MyInterface.class.isAssignableFrom(B.class); is false. I'm looking for a method returning true for both classes.
Using reflection, for each class, I can loop over the methods of the interface and check if it is implemented in the class. Is there a smarter way to do this?
No you cannot do that without reflection.
And...
Interfaces are contracts
While you might be able to figure out that B indeed has methods that have the same name as those in MyInterface, you have no way to tell, if they actually do the same thing.
By implementing an interface (as B should have), you not only implement the methods of that interface, but you commit on providing the results in a way that is intended. Having a method of the same name with same parameters will just not do in that situation.
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