9

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?

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 1
    http://stackoverflow.com/questions/1067352/can-set-enum-start-value-in-java – Dave Newton Jan 28 '12 at 20:17
  • [And this, which directly addressing storing enums to the DB](http://stackoverflow.com/questions/229856/ways-to-save-enums-in-database). – Dave Newton Jan 28 '12 at 20:31
  • @DaveNewton if I use an enumset, I can't save it the same way since getting the name won't make sense if I have OR'd 3 enum values no? – Blankman Jan 29 '12 at 20:04
  • [And this, which directly addresses storing `EnumSets` to a DB](http://stackoverflow.com/questions/2199399/storing-enumset-in-a-database). – Dave Newton Jan 29 '12 at 20:09

1 Answers1

12

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.

Paul
  • 19,704
  • 14
  • 78
  • 96