views:

1681

answers:

4

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

A: 

Not having my Java-environment Eclipse running, have you tried just "@Settings", without the parentheses?

Henrik Paul
A: 

if used with a method:

@Settings public void myMethod() { }

Now your annotation is initialized with default values.

Florin
Best workaround sofar. Still looking for a cleaner solution.
Adrian
+5  A: 

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());
Adrian
+1  A: 

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 ( ) ) ;
    }
}
emory
Local classes, I keep forgetting about them, nice hack!
Adrian