在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#背景)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
EnumSet
轻松完成此操作You can easily do it using
EnumSet
这是另一个选项,与序数解类似,只是您可以使用 |和&运算符:
或:
This is another option, which is similar to the ordinal solution, except that you can use the | and & operators with this:
or:
虽然我不推荐它,但您可以请求枚举的 ordinal() 并将其用于位操作。当然,由于您无法定义枚举的序数,因此您必须插入虚假值才能获得正确的序数。
请注意,需要引入虚假枚举,以便
While i wouldn't recommend it, you can ask for the ordinal() of an enum and use that for bit operations. Of course since you can't define what the ordinal is for an enum, you have to insert bogus values to get the ordinals right
Notice a Bogus enum needed to be introduced so that
如果您停留在 Java 7 之前的时代 (Android),您可以尝试以下代码:
}
If you stuck in the pre Java 7 Era (Android) you can try the following code:
}
据我所知,枚举类型的按位运算符未定义
As far as I know bitwise operator is undefined for enum types