THRIFT-3486 - Java generated `getFieldValue` is incompatible with `setFieldValue` for binary values
Client: Java
Patch: BCG
This closes #743
diff --git a/compiler/cpp/src/generate/t_java_generator.cc b/compiler/cpp/src/generate/t_java_generator.cc
index 9080368..f711f2d 100644
--- a/compiler/cpp/src/generate/t_java_generator.cc
+++ b/compiler/cpp/src/generate/t_java_generator.cc
@@ -2064,12 +2064,23 @@
t_type* type,
string field_name,
string cap_name) {
+ const bool is_binary = type->is_base_type() && ((t_base_type*)type)->is_binary();
indent(out) << "case " << constant_name(field_name) << ":" << endl;
indent_up();
indent(out) << "if (value == null) {" << endl;
indent(out) << " unset" << get_cap_name(field_name) << "();" << endl;
indent(out) << "} else {" << endl;
+ if (is_binary) {
+ indent_up();
+ indent(out) << "if (value instanceof byte[]) {" << endl;
+ indent(out) << " set" << cap_name << "((byte[])value);" << endl;
+ indent(out) << "} else {" << endl;
+ }
indent(out) << " set" << cap_name << "((" << type_name(type, true, false) << ")value);" << endl;
+ if (is_binary) {
+ indent(out) << "}" << endl;
+ indent_down();
+ }
indent(out) << "}" << endl;
indent(out) << "break;" << endl << endl;
diff --git a/lib/java/test/org/apache/thrift/TestStruct.java b/lib/java/test/org/apache/thrift/TestStruct.java
index b0dffc8..3379ed1 100644
--- a/lib/java/test/org/apache/thrift/TestStruct.java
+++ b/lib/java/test/org/apache/thrift/TestStruct.java
@@ -308,12 +308,40 @@
object.toString());
}
+ private static void assertArrayEquals(byte[] expected, byte[] actual) {
+ if (!java.util.Arrays.equals(expected, actual)) {
+ fail("Expected byte array did not match actual.");
+ }
+ }
+
public void testBytesBufferFeatures() throws Exception {
- JavaTestHelper o = new JavaTestHelper();
+
+ final String testString = "testBytesBufferFeatures";
+ final JavaTestHelper o = new JavaTestHelper();
+
o.setReq_bin((ByteBuffer)null);
assertNull(o.getReq_bin());
+
+ o.setReq_bin(ByteBuffer.wrap(testString.getBytes()));
+ assertArrayEquals(testString.getBytes(), o.getReq_bin());
+
o.setReq_bin((byte[])null);
assertNull(o.getReq_bin());
+
+ o.setReq_bin(testString.getBytes());
+ assertArrayEquals(testString.getBytes(), o.getReq_bin());
+
+ o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, null);
+ assertNull(o.getReq_bin());
+
+ o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, testString.getBytes());
+ assertArrayEquals(testString.getBytes(), o.getReq_bin());
+
+ o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, null);
+ assertNull(o.getReq_bin());
+
+ o.setFieldValue(JavaTestHelper._Fields.REQ_BIN, ByteBuffer.wrap(testString.getBytes()));
+ assertArrayEquals(testString.getBytes(), o.getReq_bin());
}
public void testJavaSerializable() throws Exception {