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...
To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java Annotation for you. The @interface will describe the new annotation type declaration. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare some variables.
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.
To create an instance you need to create a class that implements:
java.lang.annotation.Annotation
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()
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With