[英]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;
}
How about this: 这个怎么样:
try {
interfaceClass.getMethod(method.getName(), method.getParameterTypes());
return true;
} catch (NoSuchMethodException e) {
return false;
}
If you want to avoid catching NoSuchMethodException
from Yashai's answer : 如果你想避免从Yashai的回答中捕获
NoSuchMethodException
:
for (Method ifaceMethod : iface.getMethods()) {
if (ifaceMethod.getName().equals(candidate.getName()) &&
Arrays.equals(ifaceMethod.getParameterTypes(), candidate.getParameterTypes())) {
return true;
}
}
return false;
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;
}
}
:) :)
为了使您的方法更健壮,您可能还想检查Class#isInterface()
是否为给定类返回true
,否则抛出IllegalArgumentException
。
请参阅Method#getDeclaringClass() ,然后将Class对象与预期的接口进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.