2

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 :)

Maroun
  • 91,013
  • 29
  • 181
  • 233
Adelin
  • 16,512
  • 24
  • 100
  • 152

3 Answers3

3

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));
    }
}
Moritz Petersen
  • 12,297
  • 3
  • 36
  • 43
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.

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
1

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

Enum TimeStatus {
DAY,NIGHT 
}


byte[] bytes = toBytes(TimeStatus.DAY.name());
Adelin
  • 16,512
  • 24
  • 100
  • 152