THRIFT-702. TUnion's toString method throws NPE if the union is unset
authorBryan Duxbury <bryanduxbury@apache.org>
Fri, 12 Feb 2010 22:49:40 +0000 (22:49 +0000)
committerBryan Duxbury <bryanduxbury@apache.org>
Fri, 12 Feb 2010 22:49:40 +0000 (22:49 +0000)
git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@909645 13f79535-47bb-0310-9956-ffa450edef68

lib/java/src/org/apache/thrift/TUnion.java
lib/java/test/org/apache/thrift/test/UnionTest.java

index 353e11c..625b00d 100644 (file)
@@ -195,14 +195,20 @@ public abstract class TUnion<F extends TFieldIdEnum> implements TBase<F> {
 
   @Override
   public String toString() {
-    Object v = getFieldValue();
-    String vStr = null;
-    if (v instanceof byte[]) {
-      vStr = bytesToStr((byte[])v);
-    } else {
-      vStr = v.toString();
+    String result = "<" + this.getClass().getSimpleName() + " ";
+
+    if (getSetField() != null) {
+      Object v = getFieldValue();
+      String vStr = null;
+      if (v instanceof byte[]) {
+        vStr = bytesToStr((byte[])v);
+      } else {
+        vStr = v.toString();
+      }
+      result += getFieldDesc(getSetField()).name + ":" + vStr;
     }
-    return "<" + this.getClass().getSimpleName() + " " + getFieldDesc(getSetField()).name + ":" + vStr + ">";
+
+    return result + ">";
   }
 
   private static String bytesToStr(byte[] bytes) {
index 2527f4a..1fc1522 100644 (file)
@@ -95,6 +95,10 @@ public class UnionTest {
 
     union = TestUnion.enum_field(SomeEnum.ONE);
     union.hashCode();
+
+    union = new TestUnion();
+    // should not throw an exception
+    union.toString();
   }