Assuming you have looked at Serialization Utils from Apache Commons, you could understand that there should be some sort of class based object to be an input for any serialization algorithm.
However you want to avoid having a separate dedicated class to store and retrieve data (if I'm wrong clarify me). One possible workaround is to use a built-in class in java to encapsulate the data for you.
For example you could put your data fields in a List (ArrayList
) or even better a Map (HashMap
). Then you could serialize the map object so that it can be passed around. The good thing is these classes are already built into java so you don't need to create a separate class just for the sake of serialization.
Here is a sample example code:
import org.apache.commons.lang3.SerializationUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
class Abc {
short var1; // [11, 10]
int var2; // [17, 05, 00, 0a]
byte var3; // [01]
byte var4; // [02]
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<>();
map.put("var1", var1);
map.put("var2", var2);
map.put("var3", var3);
map.put("var4", var4);
return map;
}
public byte[] serializeMap() {
return SerializationUtils.serialize((Serializable) toMap());
}
public Map<String, Object> deSerializeMap(byte[] serializedObject) {
return SerializationUtils.deserialize(serializedObject);
}
public void setParams(Map<String, Object> deSerializedObject) {
this.var1 = (short) deSerializedObject.get("var1");
this.var2 = (int) deSerializedObject.get("var2");
this.var3 = (byte) deSerializedObject.get("var3");
this.var4 = (byte) deSerializedObject.get("var4");
}
}
public class Test2 {
public static void main(String[] args) {
Abc obj = new Abc();
obj.var1 = 10000;
obj.var2 = 500000;
obj.var3 = 2;
obj.var4 = 30;
Abc newObj = new Abc();
newObj.setParams(newObj.deSerializeMap(obj.serializeMap()));
System.out.printf("var1: %s\nvar2: %s\nvar3: %s\nvar4: %s\n", newObj.var1, newObj.var2, newObj.var3, newObj.var4);
}
}
As you can see here, I use obj
to create the values, then serialize it and newObj
to deserialize and assign back to the variable.
obj
could be belong to one class and you could serialize and send the values through network and can deserialize them on another object. This is possible because the HashMap is already built into Java.
Good thing here is that you don't need to have same class in both places. As long as both classes have above variables (variables don't even have to have a same name either, as long as type matches, this will work), you could implement this solution.