I am developing an enterprise Java application currently engaged in Java EE security to restrict access to certain features to specific users. I set up the application server and all that, and now I use the RolesAllowed annotation to protect the methods:
@Documented @Retention (RUNTIME) @Target({TYPE, METHOD}) public @interface RolesAllowed { String[] value(); }
When I use such annotation, it works fine:
@RolesAllowed("STUDENT") public void update(User p) { ... }
But this is not what I want, since I have to use String here, refactoring becomes difficult, and typos can occur. So instead of using String, I would like to use the Enum value as a parameter for this annotation. Enum is as follows:
public enum RoleType { STUDENT("STUDENT"), TEACHER("TEACHER"), DEANERY("DEANERY"); private final String label; private RoleType(String label) { this.label = label; } public String toString() { return this.label; } }
So, I tried using Enum as a parameter as follows:
@RolesAllowed(RoleType.DEANERY.name()) public void update(User p) { ... }
But then I get the following compiler error, although Enum.name just returns a string (which is always constant, right?).
The value of the RolesAllowed.value annotation attribute must be a constant expression `
The next thing I tried is to add an extra final line to my Enum:
public enum RoleType { ... public static final String STUDENT_ROLE = STUDENT.toString(); ... }
But this also does not work as a parameter, leading to the same compiler error:
How can I achieve the desired behavior? I even implemented my own interceptor to use my own annotations, which is nice, but too many lines of code for such a small problem.
RENOUNCEMENT
This question was originally a Scala question. I found out that Scala is not the source of the problem, so I will try to do this in Java first.