java 将字节转换为枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5542367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cast byte to enum
提问by Darkhydro
I have the following code:
我有以下代码:
public enum PortableTypes { Boolean, etc...};
public void testConversion() {
byte b = 5;
PortableTypes type = (PortableTypes)b;
}
When I compile, I am told that these are inconvertible types. I was unaware that something as simple as this would be left out of java. Am I missing something, or does Java just not support casting into an enum at all? I tested with an int as well, and it failed.
当我编译时,我被告知这些是不可转换的类型。我不知道像这样简单的事情会被排除在 java 之外。我是否遗漏了什么,或者 Java 根本不支持转换为枚举?我也用 int 进行了测试,但失败了。
If this is not supported, what is the easiest workaround?
如果这不受支持,最简单的解决方法是什么?
EDIT:
编辑:
Since everyone keeps complaining about "bad design", I'll explain a little further. I am using an enum to represent the types that you can send using my TcpServer. The packet is sent with this type, and on the receiving side I look at the type and use it to convert the bytes that are read from the packet into usable data. Obviously you can't send an enum using an OutputStream, so I need to convert the enum value into a numerical value to be sent. I disagree with the idea that this is "bad design", I think that Enums are indeed supposed to be used for exactly this purpose, but that this design does not work in Java because it is strongly typed.
由于每个人都在抱怨“糟糕的设计”,我将进一步解释一下。我正在使用枚举来表示您可以使用我的 TcpServer 发送的类型。数据包以这种类型发送,在接收端我查看类型并使用它将从数据包中读取的字节转换为可用数据。显然您不能使用OutputStream 发送枚举,因此我需要将枚举值转换为要发送的数值。我不同意这是“糟糕的设计”的想法,我认为 Enums 确实应该用于这个目的,但是这种设计在 Java 中不起作用,因为它是强类型的。
采纳答案by corsiKa
Your most effective solution would be to pass messages back and forth with an ObjectOutputStream
. This is good for a number of reasons.
最有效的解决方案是使用ObjectOutputStream
. 出于多种原因,这很好。
- Built in
enum
serialization - Extendability to more complex message passing is smoother
- The ability to pass in callbacks and parameters is baked in as well!
- 内置
enum
序列化 - 更复杂的消息传递的可扩展性更平滑
- 传入回调和参数的能力也被烘焙了!
回答by rsenna
You're probably thinking of enum
as something like we have in c/C++ or C#, which is basically a syntax sugar for declaring constants.
您可能会想到enum
像我们在 c/C++ 或 C# 中所做的那样,它基本上是用于声明常量的语法糖。
Java's enum
is a completely different beast though... It is a built-in implementation of the Typesafe Enum pattern. Since it is strongly typed, it is not possible to directly cast a enum from a byte, or even from an integer.
不过,Javaenum
是一个完全不同的野兽……它是Typesafe Enum 模式的内置实现。由于它是强类型的,因此不可能直接从字节甚至整数转换枚举。
But all enums are complete classes in Java, so nothing stops you from implementing an additional method that does that conversion for you.
但是所有枚举都是 Java 中的完整类,因此没有什么可以阻止您实现一个额外的方法来为您进行转换。
Hope it helps.
希望能帮助到你。
Edit:Again, I'm not a Java programmer, but I guess something like this would work:
编辑:同样,我不是 Java 程序员,但我想这样的事情会起作用:
public enum PortableTypes {
Boolean,
Type2,
Type3;
public static PortableTypes convert(byte value) {
return PortableTypes.values()[value];
}
};
public void testConversion() {
byte b = 5;
PortableTypes type = PortableTypes.convert(b);
}
Let me know if it works.
让我知道它是否有效。
回答by bmargulies
Java enums have ordinals to help you out.
Java 枚举有序数来帮助你。
To get from a constant to a number, call WHATEVER.ordinal()
. It returns the index of the constant in the declaration order. So, for:
要将常量转换为数字,请调用WHATEVER.ordinal()
。它返回声明顺序中常量的索引。因此对于:
enum Underwear { BRIEFS, BOXERS };
Underwear.BRIEFS.ordinal()
is 0, and Underwear.BOXERS.ordinal()
is 1.
Underwear.BRIEFS.ordinal()
为 0,Underwear.BOXERS.ordinal()
为 1。
To get from a number to the enum object, call values()
and index the returned array.
要从数字获取枚举对象,请调用values()
并索引返回的数组。
The horse's mouth here is: http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html
这里的马嘴是:http: //download.oracle.com/javase/6/docs/api/java/lang/Enum.html
回答by Beez
Or write a static getter method:
或者写一个静态的getter方法:
PortableTypes.get(b);
public static PortableTypes get(byte b) {
return PortableTypes.values()[b];
}
回答by Daniel B. Chapman
An enum is designated a type (though it defaults to a value of int usually in persistence etc...) it actually has a type. The bigger question is why you want to cast it as I would file it under "Bad practice" generally. Strong typing is a major advantage of modern languages.
枚举被指定为一种类型(尽管它通常在持久性等中默认为 int 值......)它实际上有一个类型。更大的问题是你为什么要像我一般将它归档在“不良做法”下一样投射它。强类型是现代语言的一大优势。
If you just need a byte value read up on enum design patterns in Java.
如果您只需要读取 Java 中枚举设计模式的字节值。
If you need the value you can do something like:
如果您需要该值,您可以执行以下操作:
enum SomeEnum
{
a((byte)0x01),
b((byte)0x02),
c((byte)0x03),
d((byte)0x04);
byte byteVal;
SomeEnum(byte b)
{
byteVal = b;
}
//Continued long winded example
public MyNum replacementValueOf(byte b)
{
for(MyNum num : MyNum.values())
if(b == num.getByte())
return num;
throw new RuntimeException("Your byte " + b + " was not a backing value for MyNum.");
}
}
I was giving an in-depth answer, but I agree with the posts above, rethink the design pattern.
我给出了一个深入的答案,但我同意上面的帖子,重新思考设计模式。
回答by Chad La Guardia
You could try making a method for your enum that takes in a byte. It might look something like this:
您可以尝试为您的枚举创建一个接收一个字节的方法。它可能看起来像这样:
public enum PortableTypes {
Boolean, //etc....
Int;
public statc PortableTypes fromByte(byte b) {
for(PortableTypes t : values())
{
if(t.ordinal() == (int)b)
return t;
}
return null; //or throw exception
}
}
I don't have an IDE handy right now, but I believe something like this would work. Hope this helps.
我现在手边没有 IDE,但我相信这样的事情会奏效。希望这可以帮助。
回答by Patrick
I'm not sure it's a good idea to do this.
You could do PortableTypes.values()[b]
but it would be better to rethink the design.
我不确定这样做是否是个好主意。你可以这样做,PortableTypes.values()[b]
但最好重新考虑设计。
回答by user unknown
You can only cast from a super type to a derived type, if the type is in fact a derived type. Enums aren't kinds of Byte or vice versa.
如果类型实际上是派生类型,则只能从超类型转换为派生类型。枚举不是字节类型,反之亦然。