Use Enum type as a value parameter for @RolesAllowed-Annotation

I don't think your approach of using enums is going to work. I found that the compiler error went away if I changed the STUDENT_ROLE field in your final example to a constant string, as opposed to an expression:

public enum RoleType { 
  ...
  public static final String STUDENT_ROLE = "STUDENT";
  ...
}

However, this then means that the enum values wouldn't be used anywhere, because you'd be using the string constants in annotations instead.

It seems to me that you'd be better off if your RoleType class contained nothing more than a bunch of static final String constants.


To see why your code wasn't compiling, I had a look into the Java Language Specification (JLS). The JLS for annotations states that for an annotation with a parameter of type T and value V,

if T is a primitive type or String, V is a constant expression.

A constant expression includes, amongst other things,

Qualified names of the form TypeName . Identifier that refer to constant variables

and a constant variable is defined as

a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression


How about this?

public enum RoleType {
    STUDENT(Names.STUDENT),
    TEACHER(Names.TEACHER),
    DEANERY(Names.DEANERY);

    public class Names{
        public static final String STUDENT = "Student";
        public static final String TEACHER = "Teacher";
        public static final String DEANERY = "Deanery";
    }

    private final String label;

    private RoleType(String label) {
        this.label = label;
    }

    public String toString() {
        return this.label;
    }
}

And in annotation you can use it like

@RolesAllowed(RoleType.Names.DEANERY)
public void update(User p) { ... }

One little concern is, for any modification, we need to change in two places. But since they are in same file, its quite unlikely to be missed. In return, we are getting the benefit of not using raw strings and avoiding the sophisticated mechanism.

Or this sounds totally stupid? :)