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
  • 94,125
  • 30
  • 188
  • 241
Adelin
  • 18,144
  • 26
  • 115
  • 175

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,902
  • 3
  • 38
  • 45
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
  • 525,659
  • 79
  • 751
  • 1,130
1

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

Enum TimeStatus {
DAY,NIGHT 
}


byte[] bytes = toBytes(TimeStatus.DAY.name());
Adelin
  • 18,144
  • 26
  • 115
  • 175