How to cast enum to byte array?

2019-07-16 10:50发布

Is there anyway to cast enum to byte array? I am currently using Hbase and in HBase everything should be converted to byte array in order to be persisted so I need to cast an enum value to byte array :)

3条回答
Evening l夕情丶
2楼-- · 2019-07-16 11:16

You could create a simple utility class to convert the enum's name to bytes:

public class EnumUtils {
    public static byte[] toByteArray(Enum<?> e) {
        return e.name().getBytes();
    }
}

This is similar to your approach, but even cleaner (and a bit more typesafe, because it is only for enums).

public enum Colours {
    RED, GREEN, BLUE;
}

public class EnumUtilsTest {
    @Test
    public void testToByteArray() {
        assertArrayEquals("RED".getBytes(), EnumUtils.toByteArray(Colours.RED));
    }
}
查看更多
神经病院院长
3楼-- · 2019-07-16 11:23

If you have less than 256 enum values you could use the ordinal or a code.

enum Colour {
    RED('R'), WHITE('W'), BLUE('B');

    private final byte[] code;

    Colour(char code) {
       this.code = new byte[] { (byte) code };
    }

    static final Colour[] colours = new Colour[256];
    static {
        for(Colour c: values())
           colours[c.getCode()[0]] = c;
    }

    public byte[] getCode() {
       return code;
    }

    public static Colour decode(byte[] bytes) {
       return colours[bytes[0]];
    }
}

BTW This uses a 1 byte array and creates no garbage in the process.

查看更多
乱世女痞
4楼-- · 2019-07-16 11:23

Well I solved my problem by using name() method. For example :

Enum TimeStatus {
DAY,NIGHT 
}


byte[] bytes = toBytes(TimeStatus.DAY.name());
查看更多
登录 后发表回答