作爲sje397的答案的替代方法,您可以編寫一個簡單的具體類,類似Reference
。將參考字段本身設置爲null
以指示未設置或未定義。
public class Ref<T> {
private T value;
/**
* Sets the reference
* @param value the new value
*/
public void set(T value) {
this.value = value;
}
/**
* Get the referenced value
* @return the value
*/
public T get() {
return this.value
}
/**
* Syntatic sugar factory
* @return a Ref<T>
*/
public static Ref<T> to(T value) {
Ref<T> ref = new Ref<T>();
ref.set(value);
return ref;
}
}
使用,如:
public class A {
Ref<Integer> int1;
Ref<Boolean> bool1;
// etc.
}
int1
最初將null
或取消。要設置它,只是去:
a.int1 = Ref.to(someInt);
要設置null
值:
if (a.int1 != null) {
a.int1.set(null);
} else {
a.int1 = Ref.to(null);
}
來取消,那麼就設置參考自身null
。
這種方法的主要區別是跟蹤設置/取消設置狀態的變量較少。但是,這需要對字段本身進行空值檢查,如上所示。
我個人會選擇這種方法,如果值設置後相對不變。也就是說,它們要麼未設置,要麼設置爲不變的值(可能爲null
),在這種情況下,我會完全刪除set()
方法。
你會如何爲'Boolean'定義'不可達值'? – sje397
目的是什麼? –
@ sje397,是的,這種方法不適用於布爾值。 – Ramesh