Use UUID in annotation interface as default value

Denis Stephanov :

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.

MyStackRunnethOver :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=4336&siteId=1