问题
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 :)
回答1:
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));
}
}
回答2:
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.
回答3:
Well I solved my problem by using name()
method. For example :
Enum TimeStatus {
DAY,NIGHT
}
byte[] bytes = toBytes(TimeStatus.DAY.name());
来源:https://stackoverflow.com/questions/21108509/how-to-cast-enum-to-byte-array