Create Annotation instance with defaults, in Java
had the same issue, i solved it as follows.
public static FieldGroup getDefaultFieldGroup() {
@FieldGroup
class settring {
}
return settring.class.getAnnotation(FieldGroup.class);
}
To create an instance you need to create a class that implements:
java.lang.annotation.Annotation
- and the annotation you want to "simulate"
For example:
public class MySettings implements Annotation, Settings
But you need to pay special attention to the correct implementation of equals
and hashCode
according to the Annotation
interface.
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/annotation/Annotation.html
If you do not want to implement this again and again then have a look at the javax.enterprise.util.AnnotationLiteral class. That is part of the CDI(Context Dependency Injection)-API. (@see code)
To get the default values you can use the way that is described by akuhn (former known as: Adrian).
Settings.class.getMethod("a").getDefaultValue()
I compile and ran below with satisfactory results.
class GetSettings {
public static void main (String[] args){
@Settings final class c { }
Settings settings = c.class.getAnnotation(Settings.class);
System.out.println(settings.aaa());
}
}
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()
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());