Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast byte to enum

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.

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.

like image 800
Darkhydro Avatar asked Dec 02 '22 02:12

Darkhydro


1 Answers

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.

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.

But all enums are complete classes in Java, so nothing stops you from implementing an additional method that does that conversion for you.

Hope it helps.

Edit: Again, I'm not a Java programmer, but I guess something like this would work:

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.

like image 152
rsenna Avatar answered Dec 18 '22 18:12

rsenna