[英]Getting the actual class used for a MethodInvocation rather than the declaring class
我正在挖掘一个Web应用程序,以解决一些问题。 该应用程序使用Tomcat,Jersey和Guice。 其中一个问题发生在用于授权目的的MethodInterceptor中。 这是方法,修剪到相关部分:
public Object invoke(MethodInvocation invoc) throws Throwable {
// ...
//Check that the annotation actually exists
if(! invoc.getMethod().getDeclaringClass().isAnnotationPresent(Tool.class))
{
throw new BaseException("...");
}
// ...
}
现在的问题是,某些“面向Web”的方法是从父类继承的,而不会在子级中被覆盖。 如果我正确理解了getDeclaringClass(),它将在这种情况下返回父类,但我们真正想要的是子类。 一些测试似乎证实了这一点 - 如果我覆盖子类中的方法一切都很好,但如果我没有放入覆盖,则抛出异常。
那么,给定一个MethodInvocation对象,有没有办法将它追溯到实例化的“实际”类,而不是声明方法的类? 还是需要一些其他方法? 最糟糕的情况是,我可以根据需要注释每个方法,而不是注释类。
对不起,如果这是一个冗长的问题,一个简单的答案 - 我的Java非常生疏。
很简单,需要在MethodInvocation上使用getThis().getClass()
而不是getMethod().getDeclaringClass()
:
if(! invoc.getThis().getClass().isAnnotationPresent(Tool.class))
{
throw new BaseException("...");
}
虽然在我的情况下,Guice通过放入一个自动生成的子类(例如,一个以“$$ EnhancerByGuice ...结尾的类名”来复杂化了一些东西。这是通过使用getSuperclass()
在树上移动来修复的:
if(! invoc.getThis().getClass().getSuperclass().isAnnotationPresent(Tool.class))
{
throw new BaseException("...");
}
看起来答案是否定的。我创建了简单的测试来检查它:
class Run implements Runnable {
@Override
public void run() {
}
}
class Run2 extends Run{}
Method method = Run2.class.getMethods()[0];
System.out.println(method);
正如我们在调试窗口中看到的那样,方法没有Run2类的任何信息:
我想最好坚持使用其注释的实际方法,而不是在调用这些方法的实际类实例上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.