private final static int NONE = 0; public final static int READONLY = 1 << 0; // 001 public final static int HIDDEN = 1 << 1; // 010 public final static int CRYPT = 1 << 2; // 100
private int property = NONE;
public FileProperty(int property) { this.property = property; }
FileProperty p = new FileProperty(FileProperty.READONLY);
print("init after add READONLY:", p); p.addProperty(FileProperty.CRYPT);
print("after add CRYPT:", p);
print("has CRYPT after add CRYPT:", p.hasProperty(FileProperty.CRYPT));
print("has HIDDEN after add CRYPT:", p.hasProperty(FileProperty.HIDDEN)); p.addProperty(FileProperty.HIDDEN);
print("after add HIDDEN:", p);
print("has HIDDEN after add HIDDEN:", p.hasProperty(FileProperty.HIDDEN)); p.removeProperty(FileProperty.CRYPT);
print("after remove CRYPT:", p);
print("has CRYPT after remove CRYPT:", p.hasProperty(FileProperty.CRYPT));
}
private static void print(String name, Object obj) {
System.out.printf("%-30s %s%n", name, obj);
}
}class FileProperty {
private final static int NONE = 0;
public final static int READONLY = 1 << 0; // 001
public final static int HIDDEN = 1 << 1; // 010
public final static int CRYPT = 1 << 2; // 100
private int property = NONE;
public FileProperty(int property) {
this.property = property;
}
/**
* 添加属性
*
* @param property
*/
public void addProperty(int property) {
this.property |= property;
}
/**
* 移除属性
*
* @param property
*/
public void removeProperty(int property) {
this.property &= ~property;
}
/**
* 是否拥有属性
*
* @param property
* @return
*/
public boolean hasProperty(int property) {
return (this.property & property) != 0;
}
public int getProperty() {
return property;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("FileProperty = ");
int i = 0;
if(hasProperty(READONLY)) {
appendString(sb, "READONLY", i++);
}
if(hasProperty(HIDDEN)) {
appendString(sb, "HIDDEN", i++);
}
if(hasProperty(CRYPT)) {
appendString(sb, "CRYPT", i++);
}
if(i == 0) {
sb.append("[NONE]");
}
return sb.toString();
}
private void appendString(StringBuilder sb, String propertyName, int count) {
if(count > 0) {
sb.append(", ");
}
sb.append(propertyName);
}
}假设原有属性标志位为 00(二进制,下同),这时添加一个 HIDDEN 值 1,即 0 | 10 = 10,再添加一个 CRYPT 值 4,即 10 | 100 = 110,这时得出的位域为 110,根据常量定义每个属性在二进制位中只有一个 1,这个 1 为该值时表示拥有这个属性。上面的这段代码中有如何添加、删除,以及判断是否具有该属性,可以参考一下。