2013-10-19 38 views

回答

4

在這個問題上唯一有效的答案應該是:

你不想知道這一點。如果你需要知道,你的課程設計有問題。

但是,你至少可以通過接口反射來做到這一點。

小心你的第一次嘗試,因爲這將返回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 
    } 
} 
相關問題