Java的枚举的困惑与创建一个掩码和检查权限 [英] Java enum confusion with creating a bitmask and checking permissions

查看:118
本文介绍了Java的枚举的困惑与创建一个掩码和检查权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将这个C#权限模块,Java,但是我很困惑,我怎么能做到这一点的时候,我不能在数据库中保存的数值,然后将其转换为枚举重presentation。

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.

在C#中,我创建一个这样的枚举:

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"];

和我可以检查像权限:

if(johnsArticlePermission & ArticlePermission.CanRead == ArticlePermission.CanRead) 
{

}

我怎样才能做到这一点在Java中?
据我了解,在Java中,你可以枚举转换成数字值,然后将其转换回一个Java枚举。

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.

想法?

推荐答案

你真正需要的是在这里的的 EnumSet ,在API中是这样描述的:

What you really need here is an EnumSet, described in the API like this:

枚举集重新在内部psented为位向量$ P $。这个
  再presentation是非常紧凑且高效。在空间和时间
  此类的性能应足够好,允许其作为一个用
  高品质,类型安全的替代传统的基于INT-位
  标志。

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."

下面是EnumSet 良好概述,另:的与EnumSet 播放。

Here is a good overview of EnumSet, and another: Playing with EnumSet.

这是枚举是引擎盖下的一类,因此您可以添加方法给它。例如,

An enum is a class under the hood so you can add methods to it. For example,

public enum ArticlePermission
{
  CanRead(1),
  CanWrite(2),
  CanDelete(4),
  CanMove(16); // what happened to 8?

  private int _val;
  ArticlePermission(int val)
  {
    _val = val;
  }

  public int getValue()
  {
    return _val;
  }

  public static List<ArticlePermission> parseArticlePermissions(int val)
  {
    List<ArticlePermission> apList = new ArrayList<ArticlePermission>();
    for (ArticlePermission ap : values())
    {
      if (val & ap.getValue() != 0)
        apList.add(ap);
    }
    return apList;
  }
}

parseArticlePermissions 会给你一个列表 ArticlePermission 从整数值的对象,presumably通过或运算 ArticlePermission 对象的价值创造。

parseArticlePermissions will give you a List of ArticlePermission objects from an integer value, presumably created by ORing the value of ArticlePermission objects.

这篇关于Java的枚举的困惑与创建一个掩码和检查权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆