抽象 Java 枚举
我编写了一个应该依赖于枚举的库,但实际的枚举应该由我的库的用户定义。
在以下示例中,authorize
方法需要枚举类型Permission
的参数。
acl.authorize(userX, Permission.READ, Permission.WRITE)
我的库应该能够处理库用户定义的任意权限。但如果没有 Permission
枚举,我无法编译我的库。所以我需要像
abstract enum Permission
我的图书馆一样的东西。有解决方法可以做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将使用枚举然后实现的接口。例如,
客户端将使用类似的东西来定义枚举,例如
然后您的 API 将使用
PermissionType
类型接受参数I would use an interface which the enum would then implement. Something along the lines of
which would be used by e.g. the client to define an enum such as
Then your API would accept parameters using the
PermissionType
type以下是我建议的步骤。
public @interface Permission
让用户使用该注释来注释他的每个权限枚举:
<前><代码>@Permission
公共枚举 ConcretePermissionEnum {..}
使您的
authorize
方法如下所示:如果你希望你的 Permission 枚举有一些特定的方法,或者只是想要一个“标记”,那么你可以让用户枚举实现您的接口(而不是注释):
这将启用编译时检查,而不是运行时检查,就像注释方法一样,授权方法签名如下所示:
Here are the steps I'd suggest.
public @interface Permission
make the user annotate each of his permission enums with that annotation:
Make your
authorize
method look like: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):
This will enable a compile-time, rather than a run-time check, as with the annotation approach, with the
authorize
method signature looking like: