Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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!");
- }
- }
- }
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement