68

I defined my own custom 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

flybywire
  • 261,858
  • 191
  • 397
  • 503

3 Answers3

106

You can provide a default value for the attribute:

@Target(value={ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation  {
    Class<?> myType() default Object.class;
}
Sam Liao
  • 43,637
  • 15
  • 53
  • 61
Dan Dyer
  • 53,737
  • 19
  • 129
  • 165
6

Found it. It can't be optional, but a default can be declared like this:

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

If no default can make sense as "empty" value then that is a problem.

flybywire
  • 261,858
  • 191
  • 397
  • 503
  • If you need a default class, and you might actually need String.class as a value, consider using java.util.Void.class instead (as you can't instantiate or really use it in any other way) – Ajax Sep 22 '12 at 14:50
1

For Optional attribute you need to provide default value for that attribute you can provide default value using "default" keyword.

Note : For only one attribute you can use attribute name as value. If you use your attribute name as value you can directly pass value like this @MyCustomAnnotation(true) instead of @MyCustomAnnotation(myType = true).

See this example for more details

Dhiral Pandya
  • 10,311
  • 4
  • 47
  • 47