This sample example below better illustrates our problem.
package com.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
class TestClass1 implements Serializable {
private TestClass2 testObj;
public TestClass2 getTestObj() {
return testObj;
}
public void setTestObj(TestClass2 testObj) {
this.testObj = testObj;
}
}
class TestClass2 implements Serializable {
private Collection<String> collVal = new ArrayList<String>();
private String testStr;
public TestClass2(String testStr) {
this.testStr = testStr;
}
public Collection<String> getCollVal() {
return collVal;
}
public void setCollVal(Collection<String> collVal) {
this.collVal = collVal;
}
public String getTestStr() {
return testStr;
}
public void setTestStr(String testStr) {
this.testStr = testStr;
}
}
public class ProtostuffEmptyArrayListTest {
try {
TestClass1 test = new TestClass1();
test.setTestObj(new TestClass2("testVal"));
Schema<TestClass1> schema = RuntimeSchema.getSchema(TestClass1.class);
// Serialize with Protostuff serialization
LinkedBuffer buff = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
byte[] protostuffSerailzedContent = ProtobufIOUtil.toByteArray(test, schema, buff);
// Deserialize with Protostuff serialization
TestClass1 result1 = new TestClass1();
ProtobufIOUtil.mergeFrom(protostuffSerailzedContent, result1, schema);
// Serialize with Java serialzation.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(test);
out.close();
byte[] javaSerialzedContent = bos.toByteArray();
// Deserialize with Java serialization.
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(javaSerialzedContent));
TestClass1 result2 = (TestClass1)in.readObject();
System.out.println("BeforeDeserializedContent: " + test.getTestObj().getCollVal());
System.out.println("ProtostuffSerialization - DeserializedContent: " + result1.getTestObj().getCollVal());
System.out.println("JavaSerialization - DeserializedContent: " + result2.getTestObj().getCollVal());
} catch (Exception ex) {
System.err.println("Error: " + ex);
}
}
}
The output result from running the above code is:
BeforeDeserializedContent: []
ProtostuffSerialization - DeserializedContent: null
JavaSerialization - DeserializedContent: []
So even though TestClass2 initializes the collVal to an empty ArrayList, the protostuff deserialized result makes this collVal as null. It seems to happen when we have a non-default constructor defined in TestClass2 and no default constructor defined.
Just wanted to be sure this wasn't a behaviour in Java by default, I've tried to perform this with Java Serialization, and the deserialized result seem to be ok with Java Serialization.
Are you able to help?
Thanks
Regards
Wilson.