java - 如何找到在给定类中实现其方法的 Java 接口(interface)?

标签 java reflection methods interface

我需要的东西与大多数人想要处理的东西完全相反:我有一个带有类名和方法名的 StackTraceElement。由于该方法属于给定类实现的接口(interface),因此我需要一种方法来询问方法它源自哪个接口(interface)。

我可以调用 Class.forName(className) 也可以调用 clazz.getMethod(methodName),但是 method.getDeclaringClass()以提到的类“名称”而不是其原始接口(interface)“返回”。我不想遍历所有类的接口(interface)来查找该特定方法,这实际上会使性能无效。

--

基本上它是一个传统的广播机制。一个广播类包含一个 HashMap ,其中键是接口(interface),值是带有实现类的列表。广播器实现相同的接口(interface),以便每个方法从 HashMap 中检索实现类,遍历它们并在每个实现类上调用相同的方法。

--

很抱歉在这里添加它,但是在评论中添加它有点太长了:

我的解决方案与 Andreas 所指的类似:

StackTraceElement invocationContext = Thread.currentThread().getStackTrace()[2];
Class<T> ifaceClass = null;
Method methodToInvoke = null;
for (Class iface : Class.forName(invocationContext.getClassName()).getInterfaces()) {
  try {
    methodToInvoke = iface.getMethod(invocationContext.getMethodName(), paramTypes);
    ifaceClass = iface;
    continue;
  } catch (NoSuchMethodException e) {
    System.err.println("Something got messed up.");
  }
}

使用类似invocationContext 的结构可以创建一个拦截器,因此发送器只能包含带有空实现主体的注释方法。

最佳答案

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.

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

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;
   }
}

然后您可以查询方法声明的接口(interface),如下所示:

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]

关于java - 如何找到在给定类中实现其方法的 Java 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190642/

相关文章:

java - 如何通过执行内连接从 hbase 表中检索数据并将其带入 hive

java - 在处理开始时而不是在结束时调用 MDC.clear() 有什么缺点吗?

java - 取消投影鼠标以获取 3D 世界坐标 Libgdx

java - Java 中的动态转换和调用

java - 处理 FileNotFoundException

java - 如何配置 testsuit 始终将常量注入(inject)到类的所有实例的 @value 私有(private)字段中

c# - 如果我有 PropertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?

c# - 如何强制其他人遵守子类的特定布局?

android - Android开发中如何将变量从一个类传递到另一个类

java - 由于某种奇怪的原因,方法被调用两次?