BitWorks { static byte[] getBytesWithLength(final Object result) throws IOException { if (result == null) { return null; } final ByteArrayOutputStream byteOuputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOuputStream); try { objectOutputStream.writeObject(result); final ByteBuffer bb = ByteBuffer.allocate(4 + byteOuputStream.size()); bb.putInt(byteOuputStream.size()); bb.put(byteOuputStream.toByteArray()); return bb.array(); } finally { objectOutputStream.close(); } }  static byte[] convertUUIDToByteArray(final UUID uuid); static UUID convertByteArrayToUUID(final byte[] bytes); static byte[] convertStringsToByteArray(final String... values);  }
@Test public void getBytesWithLengthNull() throws IOException { Assert.assertNull(BitWorks.getBytesWithLength(null)); }
@Test public void getBytesWithLengthValid() throws IOException, ClassNotFoundException { String convertMe = "convertMe"; byte[] bytes = BitWorks.getBytesWithLength(convertMe); Assert.assertNotNull(bytes); Assert.assertEquals(20, bytes.length); ByteBuffer bb = ByteBuffer.wrap(bytes); Assert.assertEquals(16, bb.getInt()); byte[] stringPartInBytes = new byte[16]; bb.get(stringPartInBytes); ByteArrayInputStream bais = new ByteArrayInputStream(stringPartInBytes); ObjectInputStream ois = new ObjectInputStream(bais); String stringPart = (String) ois.readObject(); Assert.assertEquals(convertMe, new String(stringPart)); }