Обнаружение, если метод объявляется в интерфейсе в Java

Помогите мне сделать этот метод более основательным:

 /**
  * 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;
 }
7
задан Michael Myers 23 December 2009 в 20:29
поделиться

4 ответа

Как насчет этого:

try {
    interfaceClass.getMethod(method.getName(), method.getParameterTypes());
    return true;
} catch (NoSuchMethodException e) {
    return false;
}
10
ответ дан 6 December 2019 в 23:06
поделиться

Это хорошее начало:

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

:)

1
ответ дан 6 December 2019 в 23:06
поделиться

Чтобы сделать свой метод более надежным, вы, вероятно, также захотите проверить, возвращает ли Class#isInterface() truetrue для данного класса и бросить IllegalArgumentException в противном случае.

.
0
ответ дан 6 December 2019 в 23:06
поделиться

Смотрите Метод#getDeclaringClass(), затем просто сравните объекты Class с ожидаемым интерфейсом(ами).

.
-1
ответ дан 6 December 2019 в 23:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: