Visibility of enum values in Java

enums, java, visibility

Solution

Sounds like the simple answer is "No."

But, thinking about the different comments and answers (particularly by Marcelo, BlackVegetable and OldCurmudgeon), I have come up with the following workaround:

A package-private enum contains all values:

enum PackagePrivateEnum {
    PUBLIC_VALUE_1,
    PUBLIC_VALUE_2,
    PUBLIC_VALUE_3,
    PACKAGE_PRIVATE_VALUE_1,
    PACKAGE_PRIVATE_VALUE_2;
}

A second public enum contains only the public values, and directly maps these to the package-private ones:

public enum PublicEnum {
    PUBLIC_VALUE_1 (PackagePrivateEnum.PUBLIC_VALUE_1),
    PUBLIC_VALUE_2 (PackagePrivateEnum.PUBLIC_VALUE_2),
    PUBLIC_VALUE_3 (PackagePrivateEnum.PUBLIC_VALUE_3);

    final PackagePrivateEnum value;

    private PublicEnum(PackagePrivateEnum value) {
        this.value = value;
    }
}

Now, if I have a function that is only allowed to return one of the public values, I define it as:

public abstract PublicEnum returnSomething();

and can then use it in the package via:

PackagePrivateEnum value = returnSomething().value;

This hides the unwanted values from the public and, I believe, simultaneously minimizes coding- and performance-overhead inside the package (e.g. no switch- or if-statements, no Map-lookups, etc., just a `.value` required). In fact, with a smart compiler like GWT, the return-value should probably get "inlined" to the point that even the `.value`-lookup is removed completely, i.e. no performance-overhead at all.

Also, with this, it is possible to define an arbitrary number of different allowed subsets of a big collective enum for different contexts: I could easily define another `PublicEnum2` that exposes an entirely different set of values from the `PackagePrivateEnum`.

Problem

Is it possible to somehow mark certain `enum` values in Java as package-private, i.e. give them the default modifier? Background (only to preempt the otherwise immediate first comment "What for?" ;) ) I have a `Task`-object with different execution-methods and an execution-state that decides which method to call next. Each one of the execution-methods returns the execution-state of the next method to be called (basically a framework for executing a state-machine). I have an `enum` that contains all possible execution-states, but also contains a few "package-internal" states like "pending" or "failed" that should not be returnable by the execution-methods. I know I could manage these states in a separate variable with its own enum, but that would make the code a lot less clean as it turns a single `switch`-statement into (at least) two (and possibly a surrounding `if`). Also, I could, of course, just check the return value, but I'd rather not even make wrong ones available in the first place.

Original source