开发者

Java Enum referencing another enum

I would like to be able to define an Enum class that would include another Enum as well as its own values. For example, :

public enum A {
    A1, A2, A3;
}

public enum B{
    B1, B2, ...(somehow define references to all values in enum A)
}
开发者_如何学编程

such that any values contained in enum B must be either defined initself (such as B1, B2) or any values of enum A.

Thanks,


Such that B is the union of A and B? That's not possible without B extending A, which is not supported in java. The way to proceed is to create an enum which contains the combined values of A and B, e.g.,

enum C {
    A1, A2, A3, B1, B2;
}


Something like this?

enum A {
    A1, A2;
}

enum B {
    B1(null),
    B2(null),
    A1(A.A1),
    A2(A.A2);

    private final A aRef;
    private final B(A aRef) {
        this.aRef = aRef;
    }
}


Typically, since we are working in java, and usually proscribe to OO design, you could get this functionality through extension. However, enums extend java.lang.Enum implicitly and therefore cannot extend another class.

This means extensibility for enums most be derived from a different source.

Joshua Bloch addesses this in Effective Java: Second Edition in item 34, when he presents a shared interface pattern for enums. Here is his example of the pattern:

   public interface Operation {
        double apply(double x, double y);
    }

    public enum BasicOperation implements Operation {
        PLUS("+") {
            public double apply(double x, double y) { return x + y; }
        },
        MINUS("-") {
            public double apply(double x, double y) { return x - y; }
        },
        TIMES("*") {
            public double apply(double x, double y) { return x * y; }
        },
        DIVIDE("/") {
            public double apply(double x, double y) { return x / y; }
    }

This is about as close as you can get to shared state when it comes to enums. As Johan Sjöberg said above, it might just be easiest to simply combine the enums into another enum.

Best of luck!


The closest you can get is to have A and B implement some shared interface.

enum A implements MyEnum{A1,A2}
enum B implements MyEnum{B1,B2}

MyEnum e = B.B1;

This solution wont work with the switch statement nor with the optimised enum collections.

Your use-case is not supported by the java enum implementation, it was either to complex to implement (compared to its usefulness) or it didn't come up (none of the few languages that I know support this directly).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜