代码之家  ›  专栏  ›  技术社区  ›  Salem Masoud

如何在Java中将枚举转换为字节数组?

  •  1
  • Salem Masoud  · 技术社区  · 6 年前

    我想在爪哇中的字节数组中投一个枚举值,我在StAcExopp:

    How to cast enum to byte array?

    但是,它没有帮助。

    我想遍历枚举的所有元素,并将它们强制转换为字节数组或强制转换整个枚举一次。

    2 回复  |  直到 6 年前
        1
  •  1
  •   AxelH    6 年前

    一个以字节表示的实例基本上是一个序列化,所以我想您可以简单地使用它

    enum MyEnum implements Serializable {
        A
    }
    

    并将其序列化为 byte[] ,你可以用这个 source code from Taylor Leese 我改进了一点:

    这将允许我们序列化 Serializable 实例

    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();
        }
    }
    

    有了这个,我们可以再次将字节[]转换成一个实例(Carefull使用类send,这可能引发一些强制转换异常

    @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();
        }
    }
    

    我们可以测试:

    public static void main(String[] args) throws Exception {
        byte[] serial = serial(Enum.A);
        Enum e = unserial(serial, Enum.class);
    
        System.out.println(e);
    }
    

    我们可以注意到 enum 总是可序列化的,因此 implements 没必要,但我觉得这样比较安全。

        2
  •  0
  •   Michal    6 年前

    也许这有帮助

    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());
        }
    
    }