// Object must be Serializable
 public static byte[] objectToByteArray(Object obj) throws NotSerializableException {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     ObjectOutputStream out = new ObjectOutputStream(baos);
     out.writeObject(obj);
     return baos.toByteArray();
   } catch (NotSerializableException e) {
     // this is the only IOException that
     // shouldn't signal a bizarre error...
     e.fillInStackTrace();
     throw e;
   } catch (IOException e) {
     e.printStackTrace();
     throw new Error("IOException writing to a byte array!");
   }
 }