這是另一個選項,它與序號解決方案類似,只不過您可以使用|和&運營商這樣的:
public enum Permissions {
CanBlah1(1),
CanBlah2(2),
CanBlah3(4);
public int value;
Permissions(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public static void main(String[] args) {
int userPerm = Permissions.CanBlah1.value() | Permissions.CanBlah2.value();
// check permssions
//
if((userPerm & Permissions.CanBlah1.value()) == Permissions.CanBlah1.value())
{
// do something
}
}
或:
public enum Permissions {
CanBlah1,
CanBlah2,
CanBlah3;
public int value() {
return 1<<ordinal();
}
}
public static void main(String[] args) {
int userPerm = Permissions.CanBlah1.value() | Permissions.CanBlah2.value();
// check permssions
//
if((userPerm & Permissions.CanBlah1.value()) == Permissions.CanBlah1.value())
{
// do something
}
}
而且,當然,EnumSet在引擎蓋下實現爲位掩碼。 – Ross 2010-01-01 02:43:18
他們是。它使用'long'作爲64個'Enum'字節數組,所謂'JubmoSet'。 – 2010-01-01 02:53:31