From cd43a06405c806d7ff928262da29703cde7e764f Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Wed, 17 Feb 2010 20:01:29 +0000 Subject: [PATCH] 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 --- compiler/cpp/src/generate/t_java_generator.cc | 14 +++++++++++++- .../test/org/apache/thrift/test/UnionTest.java | 4 ++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/compiler/cpp/src/generate/t_java_generator.cc b/compiler/cpp/src/generate/t_java_generator.cc index d1142e76..4b9cd479 100644 --- a/compiler/cpp/src/generate/t_java_generator.cc +++ b/compiler/cpp/src/generate/t_java_generator.cc @@ -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; diff --git a/lib/java/test/org/apache/thrift/test/UnionTest.java b/lib/java/test/org/apache/thrift/test/UnionTest.java index 1fc1522b..e17b24ad 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 @@ 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!"); -- 2.17.1