获取用于MethodInvocation的实际类而不是声明类

sup*_*ass 4 java reflection

我正在研究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("...");
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是某些“面向Web”的方法是从父类继承而没有在子类中被覆盖。如果我正确理解getDeclaringClass(),在这种情况下它将返回类,但是我们真正想要的是子类。一些测试似乎证实了这一点-如果我在子类中重写该方法,一切都很好,但是,如果我不放入重写中,则会引发异常。

因此,给定一个MethodInvocation对象,是否有办法将其追溯到实例化的“实际”类,而不是方法声明所在的类?还是需要其他方法?最坏的情况是,我可以根据需要注释每个方法,而不必注释类。

很抱歉,如果这是一个容易回答的冗长问题-我的Java很生锈。

sup*_*ass 7

足够简单,需要getThis().getClass()在MethodInvocation 上使用,而不是getMethod().getDeclaringClass()

    if(! invoc.getThis().getClass().isAnnotationPresent(Tool.class))
    {
        throw new BaseException("...");
    }
Run Code Online (Sandbox Code Playgroud)

尽管就我而言,Guice放置了一个自动生成的子类(例如,以“ $$ EnhancerByGuice ...结尾”的类名),这使事情有些复杂,这可以通过使用以下方法将其向上移动到树上来解决getSuperclass()

    if(! invoc.getThis().getClass().getSuperclass().isAnnotationPresent(Tool.class))
    {
        throw new BaseException("...");
    }
Run Code Online (Sandbox Code Playgroud)