[英]How to pass an Annotation object if there is only a Class<Annotation> is available?
Suppose there is some method like this: 假设有这样的方法:
void annotate(Annotation annotation);
What is the idiomatic way in java to pass an Annotation
object to this method if I only have the Annotation
's Class
available? 如果我只有
Annotation
的Class
可用,Java中将Annotation
对象传递给此方法的惯用方式是什么?
public @interface SomeAnnotation {
}
SomeAnnotation.getClass();
As you already mentioned annotation is just a special type of interface: 正如您已经提到的,注解只是一种特殊的接口类型:
public @interface SomeAnnotation{}
Typically you actually need an "instance" of annotation usually obtained from annotated element, eg obj.getClass().getAnnotation(SomeAnnotation.class)
. 通常,您实际上需要通常从带注释的元素(例如
obj.getClass().getAnnotation(SomeAnnotation.class)
获得的注释的“实例”。 This returns dynamic proxy that implements interface SomeAnnotation
, so all properties of annotaiton are actually methods that return current values. 这将返回实现接口
SomeAnnotation
动态代理,因此SomeAnnotation
所有属性实际上都是返回当前值的方法。
If for some reason you want to simulate this functionality you can easily do it by either creating dynamic proxy yourself or even "implementing" annotation like the following: 如果出于某种原因要模拟此功能,则可以通过自己创建动态代理甚至使用“实现”注释(如下所示)来轻松实现:
public @interface SomeAnnotation{
int value();
}
void annotate(new SomeAnnotation() {
int value() {
return 5;
}
}
The anonymous inner class create instance of your annotation like defined here: 匿名内部类创建注释的实例,如下所示:
@SomeAnnotation(5)
public class MyClass {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.