Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ~ Send an enum over a socket connection

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

like image 900
Basaa Avatar asked Feb 28 '12 13:02

Basaa


1 Answers

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

like image 141
Tomasz Nurkiewicz Avatar answered Sep 30 '22 17:09

Tomasz Nurkiewicz