创建默认注释例如,在Java中 [英] Create Annotation instance with defaults, in Java
本文介绍了创建默认注释例如,在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建以下标注的一个实例(所有领域设置为默认值)。
How can I create an instance of the following annotation (with all fields set to their default value).
@Retention( RetentionPolicy.RUNTIME )
public @interface Settings {
String a() default "AAA";
String b() default "BBB";
String c() default "CCC";
}
我试过新设置()
,但似乎并没有工作...
I tried new Settings()
, but that does not seem to work...
推荐答案
您不能创建一个实例,但至少得到默认值
You cannot create an instance, but at least get the default values
Settings.class.getMethod("a").getDefaultValue()
Settings.class.getMethod("b").getDefaultValue()
Settings.class.getMethod("c").getDefaultValue()
和然后,一个动态代理可以被用来返回默认值。这是,据我所知道的,注释的方式是通过Java本身也处理。
And then, a dynamic proxy could be used to return the default values. Which is, as far as I can tell, the way annotations are handled by Java itself also.
class Defaults implements InvocationHandler {
public static <A extends Annotation> A of(Class<A> annotation) {
return (A) Proxy.newProxyInstance(annotation.getClassLoader(),
new Class[] {annotation}, new Defaults());
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.getDefaultValue();
}
}
Settings s = Defaults.of(Settings.class);
System.out.printf("%s\n%s\n%s\n", s.a(), s.b(), s.c());
这篇关于创建默认注释例如,在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文