I have a class that receives an Object object
as a parameter. Then, I want to write two functions to serialize
, and deserialize
the given object respectively.
public class ObjectWrapper implements Serializable {
private static final long serialVersionUID = 1L;
private byte[] bytes;
private Object object;
public ObjectWrapper(Object object) {
this.object = object;
}
public ObjectWrapper setObject() throws NotSerializableException {
try {
return serialize();
} catch (NotSerializableException e) {
throw new NotSerializableException("Error setting object");
}
}
public Object getObject()
throws NotSerializableException, ClassNotFoundException {
try {
return deserialize();
} catch (NotSerializableException e) {
throw new NotSerializableException("Error getting object");
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException();
}
}
private ObjectWrapper serialize()
throws NotSerializableException {
try {
ObjectOutput out = null;
// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
out = new ObjectOutputStream(bos);
out.writeObject(object);
// Get the bytes of the serialized object
bytes = bos.toByteArray();
return new ObjectWrapper(new ObjectBytes(bytes));
} catch (IOException e) {
throw new NotSerializableException("Error serializing the object!");
}
}
private Object deserialize()
throws NotSerializableException, ClassNotFoundException {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInput in = null;
in = new ObjectInputStream(bis);
Object obj = in.readObject();
return obj;
} catch (IOException e) {
throw new NotSerializableException(
"Error deserializing the object!");
}
}
}
I also needed to write this class, in order to return an object containing only an array of bytes:
public class ObjectBytes implements Serializable{
private static final long serialVersionUID = 1L;
private byte[] object_bytes;
public ObjectBytes(byte[] object_bytes) {
this.object_bytes = object_bytes;
}
public byte[] getObjectBytes() {
return object_bytes;
}
}
What I'm struggling with is the whole process of simplifying this code, because for something this simple, I find it a bit odd to have so much code. How can this be shortened?