我需要的东西与大多数人想要处理的东西完全相反:我有一个带有类名和方法名的 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/