如何从枚举tp字节数组再回来?

时间:2017-05-09 16:33:55

标签: java

我有一个枚举

public enum Test {
  VALUE, NAME;
}

我将其转换为字节数组

byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8)

如何将其转换回枚举?

Test.valueOf(array.toString())不起作用。

2 个答案:

答案 0 :(得分:3)

var title = document.title; var blurMessage = [ "Please come back! :-( ", "Don't you love me anymore? :-(", "Fancy a cookie? ", "I'm feeling lonely :-( " ]; var intervalTimer = null; var timeoutTimer = null; window.addEventListener("blur", function () { intervalTimer = setInterval(function() { var rand = Math.floor((Math.random() * blurMessage.length)); document.title = blurMessage[rand]; timeoutTimer = setTimeout(function() { document.title = title; },4000); },12000); }); window.addEventListener("focus", function(){ clearInterval(intervalTimer); clearTimeout(timeoutTimer); document.title = title; }); 无法工作的原因是array.toString返回数组的描述,而不是使用UTF-8编码的数组中的字节构造的字符串。 toString只返回类似toString的内容,这对人类来说几乎没有任何意义。

要将字节数组转换为字符串,请使用字符串的构造函数,即采用字节数组和[B@60e53b93的构造函数。这是整个代码:

Charset

如果您从逻辑上考虑,// converting to byte array Test t = Test.VALUE; byte[] bytes = t.toString().getBytes(StandardCharsets.UTF_8); // converting back to Test String str = new String(bytes, StandardCharsets.UTF_8); Test newT = Test.valueOf(str); 可能无法满足您的期望。这是因为要将字节数组转换为字符串,您需要指定编码!当你打电话给toString时,你显然没有通过Charset对象,那么计算机怎么会知道你想要什么样的字符集呢?

答案 1 :(得分:0)

首先必须使用构造函数将数组转换回正确的Stringarray.toString()没有按照你的想法行事,只会回归胡言乱语。

byte[] array = Test.VALUE.toString().getBytes(Charsets.UTF_8);
String valueString = new String(array, Charsets.UTF_8);
Test value = Test.valueOf(valueString);