Hi all,

I've been using ByteOrder quite a bit, but something that's always annoyed me is that it's not an enum (because it predates them), and therefore cannot be easily used in switch expressions or statements. For instance, the closest I get is this, which still requires a default statement:

    var i = switch (ByteOrder.nativeOrder()) {
        case ByteOrder b when b.equals(ByteOrder.LITTLE_ENDIAN) -> 1;
        case ByteOrder b when b.equals(ByteOrder.BIG_ENDIAN)    -> 2;
        default -> throw new IllegalStateException("not supported");
    };

I know that it's also possible to use a ternary expression, but that depends on there never being a third value:

    var i = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)
            ? 1 : 2


As a little proof-of-concept I created the enum below and checked the signatures with javap. Apart from a different super class (Object -> Enum) and the extra values() and valueOf(String) methods, the two have the same fields, constructors and methods with the same signatures. And it would allow us to use this shorter switch expression:

    var i = switch (ByteOrder.nativeOrder()) {
        case LITTLE_ENDIAN -> 1;
        case BIG_ENDIAN    -> 2;
    };

So my question is: are there technical limitations that would prevent this change?


The enum I created:

    public enum ByteOrder {

        BIG_ENDIAN("BIG_ENDIAN"),
        LITTLE_ENDIAN("LITTLE_ENDIAN"),
        ;

        private final String name;

         ByteOrder(String name) {
            this.name = name;
        }

        private static final ByteOrder NATIVE_ORDER
            = Unsafe.getUnsafe().isBigEndian()
                ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;

        public static ByteOrder nativeOrder() {
            return NATIVE_ORDER;
        }

        public String toString() {
            return name;
        }
    }

Reply via email to