Search code examples
javaannotationsinstantiation

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...


Solution

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