Posted By

liqweed on 02/26/09


Tagged

testing java serialization


Versions (?)

SerializationTestUtil - Is your Java instance really is serializable?


 / Published in: Java
 

Checks whether a Java instance really is serializable and measures how big it is. Writes an object to an ObjectInputStream and then tries to read it again and assert that the original and the deserialized object are equal. On the way it outputs the size of the byte array by product so you get a rough estimate of your object's size.

  1. package com.nothingspecial.test.util;
  2.  
  3. import org.junit.Assert;
  4.  
  5. import java.io.*;
  6. import static java.text.MessageFormat.format;
  7.  
  8. public class SerializationTestUtil {
  9.  
  10. private SerializationTestUtil() {
  11. }
  12.  
  13. @SuppressWarnings({"unchecked"})
  14. public static <T> T bothWays(T vo) {
  15. final byte[] bytes = serilaze(vo);
  16. return (T) deserialize(bytes);
  17. }
  18.  
  19. public static Object deserialize(byte[] bytes) {
  20. if (bytes.length == 0) {
  21. throw new IllegalArgumentException("Cannot call deserialize without calling serialize");
  22. }
  23. Object result = null;
  24. ObjectInputStream objectInputStream = null;
  25. try {
  26. objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
  27. result = objectInputStream.readObject();
  28. } catch (Exception e) {
  29. Assert.fail(format("Could not deserialize message: {0} type {1}: ", e.getMessage(), e.getClass().getSimpleName()));
  30.  
  31. } finally {
  32. if (objectInputStream != null) {
  33. try {
  34. objectInputStream.close();
  35. } catch (IOException e) {
  36. throw new RuntimeException("W00t?! Java streams API suck..." ,e);
  37. }
  38. }
  39. }
  40. return result;
  41. }
  42.  
  43. public static byte[] serilaze(Object instance) {
  44. ObjectOutputStream outputStream = null;
  45. try {
  46. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  47. outputStream = new ObjectOutputStream(byteArrayOutputStream);
  48. outputStream.writeObject(instance);
  49. outputStream.flush();
  50. System.out.println(format("Serialized form size for [{0}] instance: {1}", instance.getClass().getName(), byteArrayOutputStream.size()));
  51. return byteArrayOutputStream.toByteArray();
  52. } catch (Exception e) {
  53. Assert.fail(format("Could not serialize {2} msg {0} type {1}", e.getMessage(), e.getClass().getSimpleName(), instance));
  54. } finally {
  55. if (outputStream != null) {
  56. try {
  57. outputStream.close();
  58. } catch (IOException e) {
  59. throw new RuntimeException("W00t?! Java streams API suck..." ,e);
  60. }
  61. }
  62. }
  63. return null;
  64. }
  65. }

Report this snippet  

You need to login to post a comment.