Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Annotation instance with defaults, in 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...

like image 391
akuhn Avatar asked Nov 05 '08 22:11

akuhn


People also ask

Can we create our own annotations in Java?

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.

What is @interface annotation in Java?

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.


2 Answers

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()

like image 71
Ralph Avatar answered Sep 24 '22 07:09

Ralph


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()); 
like image 42
akuhn Avatar answered Sep 24 '22 07:09

akuhn