4

is possible to use UUID in annotation attribute? I tried add UUID in annotation as attribute as you can see below but it gives me error Attribute value must be constant.

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    String name() default "";

    UUID guid() default UUID.random(); // there I have error
}

I also tried at least null instad of random UUID but same error.

Thank you.

Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174

1 Answers1

1

Check out the Annotation documentation (here's Wikipedia):

Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.

You could change your definition to

String guid() default UUID.random().toString();

Thanks to Holger for pointing out: that won't work either. The error is telling you that the value has to be a constant, i.e. not a method call at all.

MyStackRunnethOver
  • 4,872
  • 2
  • 28
  • 42
  • 3
    You can not specify an expression like `UUID.random().toString()` as default value. – Holger Feb 10 '20 at 18:10
  • @Holger I also tried define constant with static final and there set value, but same result – Denis Stephanov Feb 10 '20 at 18:53
  • 2
    To define a constant, it’s not enough to have a `final` variable, it also must have an initializer which is also a compile-time constant. It should be obvious that `UUID.random().toString()` can’t be a constant, semantically. You can use `String guid() default "";` and leave it up to the code using the annotation to generate a new random UUID when the string is empty. – Holger Feb 10 '20 at 18:58