KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > SettableValue


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import org.apache.commons.lang.builder.HashCodeBuilder;
7
8 import java.io.Serializable JavaDoc;
9
10 /**
11  * A simple value (of any Object type) that can be in three states, not just two:
12  * <ul>
13  * <li>Unset.</li>
14  * <li>Set, but null.</li>
15  * <li>Set, with a value.</li>
16  * </ul>
17  * This lets us handle a myriad of cases in the config where we need to distinguish between something having never
18  * been set and something having been set explicitly to null.
19  */

20 public class SettableValue implements Serializable JavaDoc {
21   
22   private Object JavaDoc value;
23   private boolean isSet;
24   
25   public SettableValue() {
26     this.value = null;
27     this.isSet = false;
28   }
29   
30   public void set(Object JavaDoc value) {
31     this.value = value;
32     this.isSet = true;
33   }
34   
35   public void unset() {
36     this.value = null;
37     this.isSet = false;
38   }
39   
40   public boolean isSet() {
41     return this.isSet;
42   }
43   
44   public Object JavaDoc value() {
45     return this.value;
46   }
47   
48   /**
49    * @returns defaultValue if value has not been set
50    */

51   public Object JavaDoc value(Object JavaDoc defaultValue) {
52     if (this.isSet) {
53       return this.value;
54     } else {
55       return defaultValue;
56     }
57   }
58   
59   public boolean equals(Object JavaDoc that) {
60     if (that == this) return true;
61     if (that == null) return false;
62     if (! (that instanceof SettableValue)) return false;
63     
64     SettableValue valueThat = (SettableValue) that;
65     if (this.isSet != valueThat.isSet) return false;
66     if ((this.value == null) != (valueThat.value == null)) return false;
67     if (this.value != null) return this.value.equals(valueThat.value);
68     else return true;
69   }
70   
71   public int hashCode() {
72     return new HashCodeBuilder().append(isSet).append(value).toHashCode();
73   }
74   
75   public Object JavaDoc clone() {
76     SettableValue out = new SettableValue();
77     if (this.isSet) out.set(this.value);
78     return out;
79   }
80   
81   public String JavaDoc toString() {
82     if (! isSet) return "<unset>";
83     if (value == null) return "<null>";
84     return value.toString();
85   }
86
87 }
Popular Tags