Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class "respects" interface without implementing it

Tags:

java

interface

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?

like image 314
888 Avatar asked May 13 '26 15:05

888


1 Answers

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.

like image 83
Jan Avatar answered May 16 '26 06:05

Jan