Помогите мне сделать этот метод более основательным:
/**
* 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;
}
Как насчет этого:
try {
interfaceClass.getMethod(method.getName(), method.getParameterTypes());
return true;
} catch (NoSuchMethodException e) {
return false;
}
Это хорошее начало:
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;
}
}
:)
Чтобы сделать свой метод более надежным, вы, вероятно, также захотите проверить, возвращает ли Class#isInterface()
truetrue
для данного класса и бросить IllegalArgumentException
в противном случае.
Смотрите Метод#getDeclaringClass(), затем просто сравните объекты Class с ожидаемым интерфейсом(ами).
.