views:

202

answers:

2
+2  Q: 

abstract java enum

I write a library that should rely on enums but the actual enum should be defined be 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?

+1  A: 

Here are the steps I'd suggest.

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

    @Permission
    public enum ConcretePermissionEnum {..}
    
  3. Make your autorize method would look like:

    public boolean autorize(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 autorize method signature looking like:

public boolean authorize(User user, PermissionInterface.. permissions)
Bozho
My library should not know the READ permission. The example shows the usage where the user of my library defines the enum. My library should only know "some element of the Permission enum".
deamon
@daemon check my update
Bozho
+5  A: 

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

Steen
As used in JDK7's "more NIO features". For example: http://download.java.net/jdk7/docs/api/java/nio/file/StandardCopyOption.html
Tom Hawtin - tackline