假设有这样的方法:
void annotate(Annotation annotation);如果我只有Annotation的Class可用,那么在java中把Annotation对象传递给这个方法的惯用方式是什么?
public @interface SomeAnnotation {
}
SomeAnnotation.getClass();发布于 2013-05-27 16:38:42
正如您已经提到的,注释只是一种特殊类型的接口:
public @interface SomeAnnotation{}
通常情况下,你实际上需要一个注释的“实例”,通常是从带注释的元素中获得的,例如obj.getClass().getAnnotation(SomeAnnotation.class)。这将返回实现接口SomeAnnotation的动态代理,因此注释的所有属性实际上都是返回当前值的方法。
如果出于某种原因你想要模拟这个功能,你可以通过自己创建动态代理或者像下面这样“实现”注解来很容易地做到:
public @interface SomeAnnotation{
int value();
}
void annotate(new SomeAnnotation() {
int value() {
return 5;
}
}匿名内部类创建注释的实例,如下所示:
@SomeAnnotation(5)
public class MyClass {
}https://stackoverflow.com/questions/16769056
复制相似问题