THRIFT-703. Attempting to hash an unset union struct results in NPE
authorBryan Duxbury <bryanduxbury@apache.org>
Wed, 17 Feb 2010 20:01:29 +0000 (20:01 +0000)
committerBryan Duxbury <bryanduxbury@apache.org>
Wed, 17 Feb 2010 20:01:29 +0000 (20:01 +0000)
git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@911162 13f79535-47bb-0310-9956-ffa450edef68

compiler/cpp/src/generate/t_java_generator.cc
lib/java/test/org/apache/thrift/test/UnionTest.java

index d1142e7..4b9cd47 100644 (file)
@@ -1024,7 +1024,19 @@ void t_java_generator::generate_union_hashcode(ofstream& out, t_struct* tstruct)
   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;
index 1fc1522..e17b24a 100644 (file)
@@ -74,6 +74,10 @@ public class UnionTest {
     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!");