1 package com.fasterxml.jackson.databind.node; 2 3 import java.io.IOException; 4 5 import com.fasterxml.jackson.core.*; 6 import com.fasterxml.jackson.databind.SerializerProvider; 7 8 9 /** 10 * This concrete value class is used to contain boolean (true / false) 11 * values. Only two instances are ever created, to minimize memory 12 * usage. 13 */ 14 public class BooleanNode 15 extends ValueNode 16 { 17 private static final long serialVersionUID = 2L; 18 19 // // Just need two instances... 20 21 public final static BooleanNode TRUE = new BooleanNode(true); 22 public final static BooleanNode FALSE = new BooleanNode(false); 23 24 private final boolean _value; 25 26 /** 27 *<p> 28 * NOTE: visibility raised to `protected` in 2.9.3 to allow custom subtypes. 29 */ BooleanNode(boolean v)30 protected BooleanNode(boolean v) { _value = v; } 31 32 // To support JDK serialization, recovery of Singleton instance readResolve()33 protected Object readResolve() { 34 return _value ? TRUE : FALSE; 35 } 36 getTrue()37 public static BooleanNode getTrue() { return TRUE; } getFalse()38 public static BooleanNode getFalse() { return FALSE; } 39 valueOf(boolean b)40 public static BooleanNode valueOf(boolean b) { return b ? TRUE : FALSE; } 41 42 @Override getNodeType()43 public JsonNodeType getNodeType() { 44 return JsonNodeType.BOOLEAN; 45 } 46 asToken()47 @Override public JsonToken asToken() { 48 return _value ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE; 49 } 50 51 @Override booleanValue()52 public boolean booleanValue() { 53 return _value; 54 } 55 56 @Override asText()57 public String asText() { 58 return _value ? "true" : "false"; 59 } 60 61 @Override asBoolean()62 public boolean asBoolean() { 63 return _value; 64 } 65 66 @Override asBoolean(boolean defaultValue)67 public boolean asBoolean(boolean defaultValue) { 68 return _value; 69 } 70 71 @Override asInt(int defaultValue)72 public int asInt(int defaultValue) { 73 return _value ? 1 : 0; 74 } 75 @Override asLong(long defaultValue)76 public long asLong(long defaultValue) { 77 return _value ? 1L : 0L; 78 } 79 @Override asDouble(double defaultValue)80 public double asDouble(double defaultValue) { 81 return _value ? 1.0 : 0.0; 82 } 83 84 @Override serialize(JsonGenerator g, SerializerProvider provider)85 public final void serialize(JsonGenerator g, SerializerProvider provider) throws IOException { 86 g.writeBoolean(_value); 87 } 88 89 @Override hashCode()90 public int hashCode() { 91 return _value ? 3 : 1; 92 } 93 94 @Override equals(Object o)95 public boolean equals(Object o) 96 { 97 /* 11-Mar-2013, tatu: Apparently ClassLoaders can manage to load 98 * different instances, rendering identity comparisons broken. 99 * So let's use value instead. 100 */ 101 if (o == this) return true; 102 if (o == null) return false; 103 if (!(o instanceof BooleanNode)) { 104 return false; 105 } 106 return (_value == ((BooleanNode) o)._value); 107 } 108 } 109