Advertisement
Guest User

Untitled

a guest
May 5th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. public class ObjectWrapper implements Serializable {
  2.  
  3. private static final long serialVersionUID = 1L;
  4. private byte[] bytes;
  5. private Object object;
  6.  
  7. public ObjectWrapper(Object object) {
  8. this.object = object;
  9. }
  10.  
  11. public ObjectWrapper setObject() throws NotSerializableException {
  12. try {
  13. return serialize();
  14. } catch (NotSerializableException e) {
  15. throw new NotSerializableException("Error setting object");
  16. }
  17. }
  18.  
  19. public Object getObject()
  20. throws NotSerializableException, ClassNotFoundException {
  21. try {
  22. return deserialize();
  23. } catch (NotSerializableException e) {
  24. throw new NotSerializableException("Error getting object");
  25. } catch (ClassNotFoundException e) {
  26. throw new ClassNotFoundException();
  27. }
  28. }
  29.  
  30. private ObjectWrapper serialize()
  31. throws NotSerializableException {
  32.  
  33. try {
  34.  
  35. ObjectOutput out = null;
  36.  
  37. // Serialize data object to a byte array
  38. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  39. out = new ObjectOutputStream(bos);
  40. out.writeObject(object);
  41.  
  42. // Get the bytes of the serialized object
  43. bytes = bos.toByteArray();
  44.  
  45. return new ObjectWrapper(new ObjectBytes(bytes));
  46.  
  47. } catch (IOException e) {
  48. throw new NotSerializableException("Error serializing the object!");
  49. }
  50.  
  51. }
  52.  
  53. private Object deserialize()
  54. throws NotSerializableException, ClassNotFoundException {
  55.  
  56. try {
  57.  
  58. ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
  59. ObjectInput in = null;
  60. in = new ObjectInputStream(bis);
  61. Object obj = in.readObject();
  62. return obj;
  63.  
  64. } catch (IOException e) {
  65. throw new NotSerializableException(
  66. "Error deserializing the object!");
  67. }
  68.  
  69. }
  70.  
  71. }
  72.  
  73. public class ObjectBytes implements Serializable{
  74.  
  75.  
  76. private static final long serialVersionUID = 1L;
  77. private byte[] object_bytes;
  78.  
  79. public ObjectBytes(byte[] object_bytes) {
  80. this.object_bytes = object_bytes;
  81.  
  82. }
  83.  
  84. public byte[] getObjectBytes() {
  85. return object_bytes;
  86. }
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement