An instance represented in bytes is basically a serialization, so I guess you could simply go with that
enum MyEnum implements Serializable {
A
}
And for the serialization into a byte[]
, you can go with this source code from Taylor Leese that I have improved a bit :
This will allow us to serialize every Serializable
instance
public static byte[] serial(Serializable s) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(s);
out.flush();
return bos.toByteArray();
}
}
With this, we can convert the byte[] into an instance again (carefull with the class send, this could throw some casting exception
@SuppressWarnings("unchecked")
public static <T extends Serializable> T unserial(byte[] b, Class<T> cl) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(b)) {
ObjectInput in = null;
in = new ObjectInputStream(bis);
return (T) in.readObject();
}
}
And we can test this :
public static void main(String[] args) throws Exception {
byte[] serial = serial(Enum.A);
Enum e = unserial(serial, Enum.class);
System.out.println(e);
}
We can note with this that enum
is always serializable, so the implements
isn't necessary but I feel this is safer that way.