create a permission bit mask in java

mrblah picture mrblah · Jan 1, 2010 · Viewed 15.1k times · Source

I want to do something like this:

public enum Permissions
{
    CanBlah1,
    CanBlah2,
    CanBlah3
}

byte[] userPerm = Permissions.CanBlah1 | Permissions.CanBlah2;

// check permssions
//
if(userPerm && Permissions.CanBlah1 == Permissions.CanBlah1)
{
      // do something
}

Can you do this in Java like that? (I'm coming from a c# background)

Answer

Chandra Patni picture Chandra Patni · Jan 1, 2010

You can easily do it using EnumSet

import java.util.EnumSet;

import static java.util.EnumSet.of;
import static java.util.EnumSet.range;
import static so.User.Permissions.CanBlah1;
import static so.User.Permissions.CanBlah2;
import static so.User.Permissions.CanBlah3;

public class User {
    public enum Permissions {
        CanBlah1,
        CanBlah2,
        CanBlah3
    }

    public static void main(String[] args) throws Exception {
        EnumSet<Permissions> userPerms = of(CanBlah1, CanBlah2);
        System.out.println(userPerms.contains(CanBlah1)); //true
        System.out.println(userPerms.contains(CanBlah2)); //true
        System.out.println(userPerms.contains(CanBlah3)); //false
        System.out.println(userPerms.containsAll(of(CanBlah1, CanBlah3))); //false
        System.out.println(userPerms.containsAll(range(CanBlah1, CanBlah2))); //true
        System.out.println(userPerms.containsAll(range(CanBlah1, CanBlah3))); //false
    }

}