Vic Vic - 7 months ago 18
Java Question

Ways to serialize a class with Object field?

I've been using a class:

public class Change {
Object affectedObj; //takes an instance of any class
String affectedFieldName;
float shift;
...

public void apply() {
affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
}
}


which I now need to serialize. Since
Object
is not serializable, how can I make my class serializable?

One thing that came to my mind is to replace
Object
with generic
<T>
type:

public class Change<T> {
T affectedObj; //takes an instance of any class
String affectedFieldName;
float shift;
...

public void apply() {
affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
}
}


But I can't judge about the downsides of this approach. If it's a good way to go what are the pitfalls here regarding serialization?

Answer

Making your class generic wont help you unless you restrict T to be Serializable by adding Change<T extends Serializable>, however it will restrict the types your class can accept.

Another option is to implement Externalizable but then you would need to implement both read() and write() and will have to serialize an unknown object anyway.

Is there any reason not to use a non java specific format such as json, thrift, msgpack or other?