Custom java annotation: add attribute optional

I defined my own annotation

@Target(value={ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { Class<?> myType(); } 

how, if at all, can I make the attribute optional

+52
java annotations metaprogramming
Aug 31 '09 at 15:13
source share
3 answers

You can specify a default value for the attribute:

 @Target(value={ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { Class<?> myType() default Object.class; } 
+83
Aug 31 '09 at 15:17
source share

Found. It may not be optional, but the default value can be declared as follows:

 @Target(value={ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { Class<?> myType() default String.class; } 

If the default value does not make sense as an "empty" value, this is the problem.

+2
Aug 31 '09 at 15:18
source share

For an additional attribute you need to specify a default value for this attribute, you can specify a default value using the default keyword.

Note. For only one attribute, the attribute name can be used as a value . If you use your attribute name as a value , you can pass that value as @MyCustomAnnotation (true) instead of @MyCustomAnnotation (myType = true).

See this example for more details.

+1
Oct 13 '13 at 7:06 on
source share



All Articles