6

What is the best way to send an enum value through sockets? Is there a way to convert an enum value to an int and vice versa? Like:

Enum values {
    value1,
    value2
}

int value = (int)value1;
And...
values value2 = (value) value;

Would be very nice to send this over the internet! Thanks all!

Bas

Basaa
  • 151
  • 2
  • 13
  • Duplicate of http://stackoverflow.com/questions/1681976/enum-with-int-value-in-java – Christian Kuetbach Feb 28 '12 at 13:05
  • No, I don't want to add attributes to values, I just want to send an Enum value that is the smame on the server & client through sockets. thanks for your comment ;) – Basaa Feb 28 '12 at 13:07
  • Try [this](http://mindprod.com/jgloss/enum.html#ORDINAL). – Piotr Praszmo Feb 28 '12 at 13:08
  • Assuming that enum is same on both sides: `int ord = value.ordina2()` on one side, `values value2 = values.values()[ord]` on other. Please, name your enum values conventionally. – lxbndr Feb 28 '12 at 13:09
  • You can use this approach mentioned here - http://stackoverflow.com/questions/5292790/convert-integer-value-to-matching-java-enum – Gangadhar Feb 28 '12 at 13:09
  • Please don't answer in comments. There's a well-documented answer below. – Wouter Lievens Feb 28 '12 at 13:12

1 Answers1

6

Either marshall to int:

int ordinal = values.value1.ordinal()

//unmarshalling
values.values[ordinal];

or to String:

String name = values.value1.name();

//unmarshalling
values.valueOf(name);

The former saves some spaces (32-bits as opposed to varying-length strings) but is harder to maintain, e.g. rearranging enum values will break ordinal() backward compatibility. On the other hand ordinal() allows you to rename enum values...

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • That (And Banthars andswer) worked fine. Now anther question: What is the Java function to get the same result as C#'s: this.cmd = (Command)BitConverter.ToInt32(data, 0); – Basaa Feb 28 '12 at 13:21
  • @Basaa: technically this should be a second question (it is more likely you will receive an answer), but have a look at this: stackoverflow.com/questions/1026761 – Tomasz Nurkiewicz Feb 28 '12 at 13:25
  • I would use the name if you can. e.g. with `dataOutput.writeUTF(value.name())` and `Enum e = Values.forName(dataInput.readUTF())` as this is more readable as well. – Peter Lawrey Feb 28 '12 at 13:43
  • Would this be the recommended/a reasonable approach, or would it be better practice to use an `ObjectOutputStream` and corresponding `ObjectInputStream` to send and receive an `enum` respectively? – Harvey Adcock Aug 07 '16 at 02:10