Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract java enum

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?

like image 224
deamon Avatar asked Feb 12 '10 11:02

deamon


2 Answers

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

like image 63
Steen Avatar answered Nov 15 '22 18:11

Steen


Here are the steps I'd suggest.

  1. write an annotation - public @interface Permission
  2. make the user annotate each of his permission enums with that annotation:

    @Permission
    public enum ConcretePermissionEnum {..}
    
  3. 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)
like image 24
Bozho Avatar answered Nov 15 '22 18:11

Bozho