deamon
deamon

Reputation: 92437

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?

Upvotes: 9

Views: 13710

Answers (2)

Bozho
Bozho

Reputation: 597106

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)

Upvotes: 1

Steen
Steen

Reputation: 6849

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

Upvotes: 21

Related Questions