Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum confusion with creating a bitmask and checking permissions

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?

like image 218
Blankman Avatar asked Jan 28 '12 20:01

Blankman


People also ask

What is a bitmask enum?

Bitmask enums are a way of organizing flags. Like having a collection of booleans without having to keep track of a dozen different variables. They are fast and compact, so generally good for network related data.

Can you assign values to enums?

Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member.


1 Answers

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

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.

Here is a more detailed explanation of EnumSet.

like image 131
Paul Avatar answered Nov 15 '22 21:11

Paul