Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
 }
like image 454
ripper234 Avatar asked Dec 23 '09 19:12

ripper234


3 Answers

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;
     }
 }

:)

like image 20
OscarRyz Avatar answered Sep 23 '22 12:09

OscarRyz


How about this:

try {
    interfaceClass.getMethod(method.getName(), method.getParameterTypes());
    return true;
} catch (NoSuchMethodException e) {
    return false;
}
like image 167
Yishai Avatar answered Sep 20 '22 12:09

Yishai


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;
like image 35
hertzsprung Avatar answered Sep 22 '22 12:09

hertzsprung