且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到在给定类中实现其方法的Java接口?

更新时间:2023-09-29 18:25:52


我有一个带有className和methodName的StackTraceElement。

我需要一种方法我可以问一下它起源于哪个接口的方法

我不想要迭代所有类的接口以找到特定的方法,这实际上会使性能无效。

I have a StackTraceElement with className and methodName.
I need a way I can ask the method which interface it originates in
I don't want to iterate through all the class' interfaces to find that particular method, that would practically nullify the performance.

我首先检查是否迭代通过所有类接口在您的用例中确实是性能关键。通常,当您具有堆栈跟踪元素时,您已处于异常状态,其中性能可能不那么重要。然后,您可以使用 Class.getInterfaces()来遍历接口并查询每个接口的声明方法,例如:

I would first check whether iterating through all the class interfaces is really performance critical in your usecase. Usually, when you have a stack trace element, you are already in an exceptional state where performance might not be that critical. You could then use Class.getInterfaces() to traverse the interfaces and query the declared methods for each interface, for example like this:

class MethodQuery {
   private Set<Class<?>> result = new HashSet<>();
   private String theMethodName;

   private void traverse(Class<?> cls) {
      for (Class<?> c : cls.getInterfaces()) {
         for (Method m : c.getDeclaredMethods()) {
            if (theMethodName.equals(m.getName())) {
               result.add(c);
            }
         }

         traverse(c);
      }
   }

   public Set<Class<?>> getInterfacesForMethod(Class<?> cls, String methodName) {
      result.clear();
      theMethodName = methodName;
      traverse(cls);
      return result;
   }
}

然后,您可以查询方法声明的接口:

You can then query which interface a method declares like this:

MethodQuery methodQuery = new MethodQuery();
Set<Class<?>> result = 
    methodQuery.getInterfacesForMethod(java.util.Vector.class, "addAll");
System.out.println(result);

结果:

[interface java.util.Collection, interface java.util.List]