Rethinking Java with bitmask creation and permission checking

I want to port this C # permission module to java, but I am confused about how to do this when I cannot save a numeric value in the database and then pass it to the enumeration view.

In C #, I create an enumeration as follows:

public enum ArticlePermission
{
     CanRead   = 1,
     CanWrite  = 2,
     CanDelete = 4,
     CanMove   = 16
}

Then I can create a permission set, for example:

ArticlePermission johnsArticlePermission = ArticlePermission.CanRead | ArticlePermission.CanMove;

Then I save it to the database using:

(int)johnsArticlePermission

Now I can read it from the database as an integer / long and make it as follows:

johnsArticlePermission = (ArticlePermission) dr["articlePermissions"];

And I can check permissions, for example:

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

}

How can i do this in java? From what I understand, in java you can convert an enumeration to a numeric value and then convert it back to a java enumeration.

Ideas?

+5
source share
1 answer

, EnumSet, API :

Enum . . , , "-" ".

EnumSet, : EnumSet.

- , . ,

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 List ArticlePermission , ORing ArticlePermission.

+6

All Articles