小编典典

在Java中创建权限位掩码

java

我想做这样的事情:

public enum Permissions
{
    CanBlah1,
    CanBlah2,
    CanBlah3
}

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

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

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


阅读 217

收藏
2020-11-13

共1个答案

小编典典

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

}
2020-11-13