Java 枚举与创建位掩码和检查权限的混淆
我想将此 c# 权限模块移植到 java,但是当我无法将数值保存在数据库中然后将其转换为枚举表示形式时,我很困惑如何执行此操作。
在 C# 中,我创建一个像这样的枚举:
public enum ArticlePermission
{
CanRead = 1,
CanWrite = 2,
CanDelete = 4,
CanMove = 16
}
然后我可以创建一个权限集,如下所示:
ArticlePermission johnsArticlePermission = ArticlePermission.CanRead | ArticlePermission.CanMove;
然后我使用以下方法将其保存到数据库中:
(int)johnsArticlePermission
现在我可以从数据库中将其作为整数/长整型读取,并将其转换为:
johnsArticlePermission = (ArticlePermission) dr["articlePermissions"];
我可以检查权限,例如:
if(johnsArticlePermission & ArticlePermission.CanRead == ArticlePermission.CanRead)
{
}
How can I do this in java? 据我了解,在java中,您可以将枚举转换为数值,然后将其转换回java枚举。
有想法吗?
I want to port this c# permission module to java, but I am confused how I can do this when I can't save the numeric value in the database and then cast it to the enumeration representation.
In c#, I create a enum like this:
public enum ArticlePermission
{
CanRead = 1,
CanWrite = 2,
CanDelete = 4,
CanMove = 16
}
I then can create a permission set like:
ArticlePermission johnsArticlePermission = ArticlePermission.CanRead | ArticlePermission.CanMove;
I then save this into the database using:
(int)johnsArticlePermission
Now I can read it from the database as an integer/long, and cast it like:
johnsArticlePermission = (ArticlePermission) dr["articlePermissions"];
And I can check permissions like:
if(johnsArticlePermission & ArticlePermission.CanRead == ArticlePermission.CanRead)
{
}
How can I do this in java?
From what I understand, in java, you can convert the enumeration into a numeric value, and then convert it back to a java enumeration.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您真正需要的是 EnumSet,API中的描述如下:
是一个底层类,因此您可以向其中添加方法。例如,
parseArticlePermissions
将为您提供ArticlePermission
的List
> 来自整数值的对象,大概是通过对ArticlePermission
对象的值进行或运算创建的。这里是更详细的 EnumSet 解释。
What you really need here is an EnumSet, described in the API like this:
An enum is a class under the hood so you can add methods to it. For example,
parseArticlePermissions
will give you aList
ofArticlePermission
objects from an integer value, presumably created by ORing the value ofArticlePermission
objects.Here is a more detailed explanation of EnumSet.