Java enum confusion with creating a bitmask and ch

2019-04-26 02:01发布

问题:

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?

回答1:

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

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."

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 will give you a List of ArticlePermission objects from an integer value, presumably created by ORing the value of ArticlePermission objects.