I would like to check if a class implements all the methods of a specific interface without directly implementing it.
ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.