Skip to content

Instantly share code, notes, and snippets.

@SoniEx2
Created May 4, 2015 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoniEx2/2c3a23a201c8a5640e82 to your computer and use it in GitHub Desktop.
Save SoniEx2/2c3a23a201c8a5640e82 to your computer and use it in GitHub Desktop.
Abstract Enums

Hello,

I'd like to talk about abstract enums. In Java, you have enums:

public enum MyEnum {
    MY_ENUM_VALUE,
    MY_OTHER_ENUM_VALUE;
}

You can't extend another enum, or make abstract enums, and an enum is defined as being tagged ENUM in bytecode and directly subclassing Enum.

My proposal is to add abstract enums, allowing you to require an enum with specific methods:

public abstract enum MyAbstractEnum {
    // cannot define values
    private final String humanReadableName;
    protected MyAbstractEnum(String humanReadableName) {
        this.humanReadableName = humanReadableName;
    }
    public final String getHumanReadableName() {
        return this.humanReadableName;
    }
}
public enum MyEnum extends MyAbstractEnum {
    MY_ENUM_VALUE("My Enum Value"),
    MY_FANCY_ENUM_VALUE("My Fancy Enum Value");
}

// somewhere else
public class ConfigurationManager<T extends MyAbstractEnum> {
    public ConfigurationManager(Class<? extends T> fields) {
        try {
            T[] values = (T[]) fields.getMethod("values").invoke(null);
            /* parse values */
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /* ... */
    public void write(OutputStream stream) {
        /* ... */
        String name = field.getHumanReadableName();
        /* ... */
    }
    /* ... */
}

And then change what's an enum to:

  • Has to be marked as ENUM
  • Has to be subclass of Enum
  • Has to have abstract superclass
  • (Hmm how can we make it so values can't be accidentally seen as an enum? Meh, add another mark: ENUM_VALUE (alternatively: has to be abstract. but that'd require extra classes to be made (NOT 1 PER VALUE THO!)))

Then I'd be able to have my enum-based config files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment