public void writeObject(ByteBuffer buffer, Object object) throws IOException { Collection collection = (Collection) object; int length = collection.size(); buffer.putInt(length); if (length == 0) return; Iterator it = collection.iterator(); Class elementClass = it.next().getClass(); while (it.hasNext()) { Object obj = it.next(); if (obj.getClass() != elementClass) { elementClass = null; break; } } if (elementClass != null) { buffer.put((byte) 1); Serializer.writeClass(buffer, elementClass); Serializer serializer = Serializer.getSerializer(elementClass); for (Object elem : collection) { serializer.writeObject(buffer, elem); } } else { buffer.put((byte) 0); for (Object elem : collection) { Serializer.writeClassAndObject(buffer, elem); } } }
/** * Converts a message to a ByteBuffer using the Serializer and the (short length) + data protocol. * If target is null then a 32k byte buffer will be created and filled. */ public static ByteBuffer messageToBuffer(Message message, ByteBuffer target) { // Could let the caller pass their own in ByteBuffer buffer = target == null ? ByteBuffer.allocate(32767 + 2) : target; try { buffer.position(2); Serializer.writeClassAndObject(buffer, message); buffer.flip(); short dataLength = (short) (buffer.remaining() - 2); buffer.putShort(dataLength); buffer.position(0); return buffer; } catch (IOException e) { throw new RuntimeException("Error serializing message", e); } }