THRIFT-703. Attempting to hash an unset union struct results in NPE

git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@911162 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/compiler/cpp/src/generate/t_java_generator.cc b/compiler/cpp/src/generate/t_java_generator.cc
index d1142e7..4b9cd47 100644
--- a/compiler/cpp/src/generate/t_java_generator.cc
+++ b/compiler/cpp/src/generate/t_java_generator.cc
@@ -1024,7 +1024,19 @@
   if (gen_hash_code_) {
     indent(out) << "@Override" << endl;
     indent(out) << "public int hashCode() {" << endl;
-    indent(out) << "  return new HashCodeBuilder().append(getSetField().getThriftFieldId()).append((getFieldValue() instanceof TEnum) ? ((TEnum)getFieldValue()).getValue() : getFieldValue()).toHashCode();" << endl;
+    indent(out) << "  HashCodeBuilder hcb = new HashCodeBuilder();" << endl;
+    indent(out) << "  hcb.append(this.getClass().getName());" << endl;
+    indent(out) << "  TFieldIdEnum setField = getSetField();" << endl;
+    indent(out) << "  if (setField != null) {" << endl;
+    indent(out) << "    hcb.append(setField.getThriftFieldId());" << endl;
+    indent(out) << "    Object value = getFieldValue();" << endl;
+    indent(out) << "    if (value instanceof TEnum) {" << endl;
+    indent(out) << "      hcb.append(((TEnum)getFieldValue()).getValue());" << endl;
+    indent(out) << "    } else {" << endl;
+    indent(out) << "      hcb.append(value);" << endl;
+    indent(out) << "    }" << endl;
+    indent(out) << "  }" << endl;
+    indent(out) << "  return hcb.toHashCode();" << endl;
     indent(out) << "}";
   } else {
     indent(out) << "/**" << endl;
diff --git a/lib/java/test/org/apache/thrift/test/UnionTest.java b/lib/java/test/org/apache/thrift/test/UnionTest.java
index 1fc1522..e17b24a 100644
--- a/lib/java/test/org/apache/thrift/test/UnionTest.java
+++ b/lib/java/test/org/apache/thrift/test/UnionTest.java
@@ -74,6 +74,10 @@
     System.out.println(union);
 
     union = new TestUnion();
+
+    // should not throw an exception here
+    union.hashCode();
+
     union.setI32_field(1);
     if (union.getI32_field() != 1) {
       throw new RuntimeException("didn't get the right value for i32 field!");