Using String.format () as the value of an annotation attribute

I have a class that has several constants:

public class SecurityConstants {
    private static final String HAS_ROLE_TEMPLATE = "hasRole('%s')";

    public static final String ROLE_USER_INTERNAL = "ROLE_USER_INTERNAL";
    public static final String HAS_ROLE_USER_INTERNAL = String.format(HAS_ROLE_TEMPLATE, ROLE_USER_INTERNAL);
}

If then I try to use HAS_ROLE_USER_INTERNALas @PreAuthorizeannotation attribute value similar to this compiler @PreAuthorize(SecurityConstants.HAS_ROLE_USER_INTERNAL), with:

The value of the PreAuthorize.value annotation attribute must be constant Expression

However, if I change HAS_ROLE_USER_INTERNALas simple String, it works fine:

public static final String HAS_ROLE_USER_INTERNAL = "hasRole('ROLE_USER_INTERNAL')";

What is the problem with using String.format()? Field staticand finalwhat could go wrong?

+5
source share
1 answer

String.format() , String.

, , .class. String.format() , .

+8

All Articles