![](/img/trans.png)
[英]Why can't we instantiate an interface or an abstract class in java without an anonymous class method?
[英]How can we identify if a method belongs to an abstract class or an interface?
我們如何確定特定方法是屬於抽象類還是屬於接口? 有沒有辦法識別它?
關於這個問題的唯一有效答案應該是:
您不想知道這一點。 如果您需要知道這一點,則您的類設計有問題。
但是,盡管如此,您至少可以通過反射來實現。
第一次嘗試時要小心,因為即使在類的接口中聲明了它,它也會返回false
。 (請參見下面的示例)
TestImpl.class.getMethod("test").getDeclaringClass().isInterface(); // false
您將需要做更多的反射魔術來獲得正確的結果,如下所示:
public class ReflectionTest {
interface Test {
void test();
}
class TestImpl implements Test {
@Override
public void test() {
}
}
private static boolean isInterfaceMethod(Class clazz, String methodName) throws NoSuchMethodException, SecurityException {
for (Class interfaze : clazz.getMethod(methodName).getDeclaringClass().getInterfaces()) {
for (Method method : interfaze.getMethods()) {
if (method.getName().equals(methodName)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
System.out.println(isInterfaceMethod(TestImpl.class, "test")); // true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.