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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With