我想做这样的事情:

public enum Permissions
{
    CanBlah1,
    CanBlah2,
    CanBlah3
}

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

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

您可以用Java这样吗? (我来自C#背景)

最佳答案

您可以使用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
    }

}

10-05 21:49