Tuesday, July 30, 2013

Extending String in Java with enums

Without extension methods in Java 8 (or without changing JVM language) one cannot extend String. Or can one?

public final class ExtendStringWithEnum {
    public static void main(final String... args) {
        out.println(format("%s: %s", APPLE, toCrAzYcAsE(APPLE)));
        out.println(format("%s: %s", BANANA, BANANA.toCrAzYcAsE()));
    }

    public enum EnumConstants {
        APPLE("apple"), BANANA("banana");
        private final String value;

        EnumConstants(final String value) {
            this.value = value;
        }

        public String toCrAzYcAsE() {
            return ExtendStringWithEnum.toCrAzYcAsE(value);
        }

        @Override
        public String toString() {
            return value;
        }
    }

    public static final class StringConstants {
        public static final String APPLE = "apple";
        public static final String BANANA = "banana";
    }

    public static String toCrAzYcAsE(final String value) {
        final StringBuilder builder = new StringBuilder(value.length());
        for (int i = 0, x = value.length(); i != x; ++i)
            builder.append(
                    0 == i % 2 ? toUpperCase(value.charAt(i))
                            : toLowerCase(value.charAt(i)));
        return builder.toString();
    }
}

Given suitable static imports, the code in "main" for APPLE is how I write it using string constants; the code for BANANA is how I write it for enum constants wrapping strings, and how I would like to write it for strings as well using the static "toCrAzYcAsE" methods. Maybe Java 9.

No comments: