我一直在使用Guice的AOP来拦截一些方法调用.我的类实现了一个接口,我想注释接口方法,以便Guice可以选择正确的方法.即使注释类型使用Inherited annotation注释,实现类也不会继承Inherited的java doc中所述的注释:
另请注意,此元注释仅导致注释从超类继承; 已实现接口上的注释无效.
这可能是什么原因?了解对象类在运行时实现的所有接口并不是一件难事,因此必须有充分的理由支持这一决策.
将当前正在执行的方法作为Method对象的最优雅方法是什么?
我的第一个明显的方法是在helper类中使用静态方法,它将加载当前线程堆栈,获取正确的堆栈跟踪元素,并从其信息构造Method元素.
是否有更优雅的方式来实现这一目标?
我有一个带注释方法的接口.注释标有@Inherited,所以我希望实现者继承它.但事实并非如此:
码:
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Example {
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
TestInterface obj = new TestInterface() {
@Override
public void m() {}
};
printMethodAnnotations(TestInterface.class.getMethod("m"));
printMethodAnnotations(obj.getClass().getMethod("m"));
}
private static void printMethodAnnotations(Method m) {
System.out.println(m + ": " + Arrays.toString(m.getAnnotations()));
}
}
interface TestInterface {
@TestAnnotation
public void m();
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface TestAnnotation {}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
public abstract void annotations.TestInterface.m():[@ annotations.TestAnnotation()]
public void annotations.Example $ 1.m():[] …