I write a library that should rely on enums but the actual enum should be defined by the user of my library.
In the following example the authorize
method requires parameters of the enum type Permission
.
acl.authorize(userX, Permission.READ, Permission.WRITE)
My library should be able to handle arbitrary permissions defined by the library user. But I cannot compile my library without a Permission
enum. So I would need something like
abstract enum Permission
in my library. Is there a workaround to do this?
I would use an interface which the enum would then implement. Something along the lines of
public interface PermissionType{}
which would be used by e.g. the client to define an enum such as
public enum Permission implements PermissionType
[...]
Then your API would accept parameters using the PermissionType
type
Here are the steps I'd suggest.
public @interface Permission
make the user annotate each of his permission enums with that annotation:
@Permission
public enum ConcretePermissionEnum {..}
Make your authorize
method look like:
public boolean authorize(User user, Enum... permissions) {
for (Enum permission : permissions) {
if (permission.getClass().isAnnotationPresent(Permission.class)){
// handle the permission
}
}
}
If you want your Permission enums to have some specific methods, or just want a 'marker', then you can make the user enums implement an interface of yours (instead of being annotated):
interface PermissionInterface {..}
enum ConcretePermission implements PermissionInterface
This will enable a compile-time, rather than a run-time check, as with the annotation approach, with the authorize
method signature looking like:
public boolean authorize(User user, PermissionInterface... permissions)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With