ripper234
ripper234

Reputation: 230008

Detecting if a method is declared in an interface in Java

Help me make this method more solid:

 /**
  * Check if the method is declared in the interface.
  * Assumes the method was obtained from a concrete class that 
  * implements the interface, and return true if the method overrides
  * a method from the interface.
  */
 public static boolean isDeclaredInInterface(Method method, Class<?> interfaceClass) {
     for (Method methodInInterface : interfaceClass.getMethods())
     {
         if (methodInInterface.getName().equals(method.getName()))
             return true;
     }
     return false;
 }

Upvotes: 7

Views: 3310

Answers (5)

hertzsprung
hertzsprung

Reputation: 9893

If you want to avoid catching NoSuchMethodException from Yashai's answer:

for (Method ifaceMethod : iface.getMethods()) {
    if (ifaceMethod.getName().equals(candidate.getName()) &&
            Arrays.equals(ifaceMethod.getParameterTypes(), candidate.getParameterTypes())) {
        return true;
    }
}
return false;

Upvotes: 2

BalusC
BalusC

Reputation: 1108692

To make your method more robust, you probably also want to check if Class#isInterface() returns true for the given class and throw IllegalArgumentException otherwise.

Upvotes: 0

user242881
user242881

Reputation:

See Method#getDeclaringClass(), then just compare Class objects with the expected interface(s).

Upvotes: -1

Yishai
Yishai

Reputation: 91871

How about this:

try {
    interfaceClass.getMethod(method.getName(), method.getParameterTypes());
    return true;
} catch (NoSuchMethodException e) {
    return false;
}

Upvotes: 12

OscarRyz
OscarRyz

Reputation: 199215

This is a good start:

Replace:

for (Method methodInInterface : interfaceClass.getMethods())
 {
     if (methodInInterface.getName().equals(method.getName()))
         return true;
 }

with:

for (Method methodInInterface : interfaceClass.getMethods()) {
     if (methodInInterface.getName().equals(method.getName())) {
         return true;
     }
 }

:)

Upvotes: 1

Related Questions