2013-10-19 37 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 
    } 
} 
相关问题