如何将枚举转换为字节数组? [英] How to cast enum to byte array?

查看:148
本文介绍了如何将枚举转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有将枚举转换为字节数组的方法?我当前正在使用Hbase,在HBase中,所有内容都应转换为字节数组以便持久保存,因此我需要将枚举值转换为字节数组:)

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

推荐答案

您可以创建一个简单的实用程序类,将枚举的名称转换为字节:

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

这篇关于如何将枚举转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆