Serializing EnumSet (with little contrib)


the default serializers do not support EnumSet. Here is a small contrib to do it ;





import java.nio.ByteBuffer;

import java.util.EnumSet;

public class EnumSetSerializer extends Serializer {

private enum Dummy { }

public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {

int length = data.getInt();

if (length == 0) {

return (T) EnumSet.noneOf(Dummy.class);


SerializerRegistration reg = Serializer.readClass(data);

Class clazz = reg.getType();

Serializer serializer = reg.getSerializer();

EnumSet set = EnumSet.noneOf(clazz);

for (int i = 0; i != length; ++i) {

set.add(serializer.readObject(data, clazz));


return (T) set;


public void writeObject(ByteBuffer buffer, Object object) throws IOException {

EnumSet set = (EnumSet)object;

int length = set.size();


if (length == 0) return;

Class enumClass = set.iterator().next().getClass();

Serializer.writeClass(buffer, enumClass);

Serializer serializer = Serializer.getSerializer(enumClass);

for (Object elem : set) {

serializer.writeObject(buffer, elem);





To use it, perform explicit registration of it like this for each of your EnumSet (the example is for my Action enum) ;


Serializer.registerClass(Action.class, new EnumSerializer());

Serializer.registerClass(EnumSet.noneOf(Action.class).getClass(), new EnumSetSerializer());


1 Like

Looks good. You might want to add support for a null EnumSet. A couple of the other serializers snag people this way too.

It’s really too bad that EnumSet doesn’t provide access to its internal bit set as that would be a lot more efficient to send. Though I suppose at the expense of some complexity that it could be recreated in code.

Hi, is this in the beta1 release? EnumSetSerializer doesn’t seem to be included in the jars.

If I try to serialize an EnumSet<>, I getting the following error:

	... 9 more```

You have to take the contribution as provided and include it in your own project. I don’t think it was ever added to core… at least I don’t think I ever saw a patch.