1

I want to cast an Enum value to a byte array in Java, I found the following post on StackOverflow:

How to cast enum to byte array?

However, it was not helpful.

I want to iterate over all the Elements of the enum and cast them to a byte array or to cast the whole enum once.

Salem Masoud
  • 411
  • 11
  • 32
  • There is no standard definition of what such a cast would do. Do you mean you want the value the name of each enum (without the type name) as a byte[] in UTF-8 encoding? – Peter Lawrey Jun 12 '18 at 11:54
  • What would casting a class to a byte[] mean? You could get the byte code for the class. – Peter Lawrey Jun 12 '18 at 11:56
  • 1
    How will you be converting the byte array back into instances of the enum? An answer to that may lead to how to convert from enum to byte array – ernest_k Jun 12 '18 at 11:56
  • I guess you could try to serialize the enum ... but why ? – AxelH Jun 12 '18 at 12:02
  • How do you even envisage such a cast? The relation between an enum and a byte array is like that between a fish and an aeroplane. If you explain *what* and *why*, and in particular giving the bigger picture, we might be able to understand what you are asking. – DodgyCodeException Jun 12 '18 at 12:34
  • @PeterLawrey I want the value of each enum (without the type name) as a byte[] in UTF-8 encoding. – Salem Masoud Jun 14 '18 at 10:53
  • @SalemMasoud in that case you want `e.name().getBytes();` – Peter Lawrey Jun 14 '18 at 18:35

2 Answers2

2

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.

AxelH
  • 14,325
  • 2
  • 25
  • 55
0

Maybe this helps

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Stackoverflow {

    public enum Test {
        TEST_1, TEST_2


    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(bytes);

        for (Test testValue : Test.values()) {
            objectOut.writeObject(testValue);
        }

        byte[] result = bytes.toByteArray();

        // check result
        ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(result));
        System.out.println(((Test) objectIn.readObject()).name());
        System.out.println(((Test) objectIn.readObject()).name());
    }

}
Michal
  • 970
  • 7
  • 11