我正在从用作标志的数据源获取一个int。示例:
private static final int EMPLOYEE = 0x00000001;
private static final int IT = 0x00000002;
private static final int MARKETING = 0x00000004;
private static final int DATA = 0x00000008;
private static final int DBAs = IT | DATA;
private static final int DATA_REPORTERS = MARKETING | DATA;
private static boolean isDba(int flag){
return (flag & DBAs) == flag;
}
private static boolean isInIT(int flag) {
return (flag & IT) == flag;
}
class Employee {
private int role;
private final String name;
//etc
}
employee = fetchEmployee()
if(isDba(employee.role)){
System.out.println("Is a DBA");
}
这似乎可以正常工作,但是我也想研究EnumSet
,以防我可以稍微简化一下代码,但对我来说似乎不是。例如,我需要拥有:
private static final int EMPLOYEE = 1; // bit 1
private static final int IT = 2; // bit 2
private static final int MARKETING = 3; // bit 3
private static final int DATA = 4; // bit 4
哪些是要设置的单个位,但我可以弄清楚如何完成以下操作:
private static final int DBAs = IT | DATA;
private static final int DATA_REPORTERS = MARKETING | DATA;
带有BitSet
因此,如何使用BitSet
正确地实现上述功能(假设BitSet
是正确的选择,因为我不需要对位集进行任何更新就可以检查标志)
我认为EnumSet比BitSet更可取,特别是如果您只需要readOnly访问。
enum EmployeeRole {
EMPLOYEE, IT, MARKETING, DATA
}
EnumSet<EmployeeRole> DBAs = EnumSet.of(IT, DATA);
EnumSet<EmployeeRole> DATA_REPORTERS = EnumSet.of(MARKETING, DATA);
class Employee {
EnumSet<EmployeeRole> roles;
boolean isDba(){
for(EmployeeRole role: roles){
if(DBAs.containsRole(role){
return true;
}
}
return false;
}
}
但是如果您将标志作为数据库中的单个字段存储在数据库中,则需要进行转换,例如使用旧的apache commons-lang EnumUtils
//write
long rolesAsLong = EnumUtils.generateBitVector(EmployeeRole.class, employee.getRoles())
//read
employee.setRoles(EnumUtils.processBitVector(EmployeeRole.class, rolesAsLong));
或者您可以为此编写自定义的休眠用户类型。这些可能会激发您的灵感:https://github.com/search?q=EnumSetUserType&type=Code