假设有这样的方法:
void annotate(Annotation annotation);
如果我只有 Annotation
的 Class
可用,那么 Java 中将 Annotation
对象传递给此方法的惯用方法是什么?
public @interface SomeAnnotation {
}
SomeAnnotation.getClass();
最佳答案
正如您已经提到的,注释只是一种特殊类型的接口(interface):
public @interface SomeAnnotation{}
通常,您实际上需要一个通常从带注释的元素获取的注释“实例”,例如obj.getClass().getAnnotation(SomeAnnotation.class)
。这将返回实现接口(interface) SomeAnnotation
的动态代理,因此 annotaiton 的所有属性实际上都是返回当前值的方法。
如果由于某种原因您想要模拟此功能,您可以通过自己创建动态代理甚至“实现”注释来轻松实现,如下所示:
public @interface SomeAnnotation{
int value();
}
void annotate(new SomeAnnotation() {
int value() {
return 5;
}
}
匿名内部类创建注释的实例,如下定义:
@SomeAnnotation(5)
public class MyClass {
}
关于java - 如果只有 Class<Annotation> 可用,如何传递 Annotation 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769056/