5

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

6
  • Duplicate of stackoverflow.com/questions/1681976/enum-with-int-value-in-java Commented Feb 28, 2012 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 ;) Commented Feb 28, 2012 at 13:07
  • Try this. Commented Feb 28, 2012 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. Commented Feb 28, 2012 at 13:09
  • You can use this approach mentioned here - stackoverflow.com/questions/5292790/… Commented Feb 28, 2012 at 13:09

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

4 Comments

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: 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
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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.