简体   繁体   中英

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

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, eg rearranging enum values will break ordinal() backward compatibility. On the other hand ordinal() allows you to rename enum values...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM