I have;
public enum Detailed { PASSED, INPROCESS, ERROR1, ERROR2, ERROR3; }
and need to convert it to the following;
public enum Simple { DONE, RUNNING, ERROR; }
So first PASSED
->DONE
and INPROCESS
->RUNNING
, but all errors should be: ERROR
. Obviously it is possible to write cases for all values, but there may be a better solution?
A cast operation is not possible, but you can write a static member function for enum1 that casts enum2 to enum1: public static Enum1 fromEnum2(Enum2 enum2) { ... } By the way, you can assign an ID to every constant of both enums which simplifies the implementation.
You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.
The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
Personally I would just create a Map<Detailed, Simple>
and do it explicitly - or even use a switch
statement, potentially.
Another alternative would be to pass the mapping into the constructor - you could only do it one way round, of course:
public enum Detailed { PASSED(Simple.DONE), INPROCESS(Simple.RUNNING), ERROR1(Simple.ERROR), ERROR2(Simple.ERROR), ERROR3(Simple.ERROR); private final Simple simple; private Detailed(Simple simple) { this.simple = simple; } public Simple toSimple() { return simple; } }
(I find this simpler than Ted's approach of using polymorphism, as we're not really trying to provide different behaviour - just a different simple mapping.)
While you could potentially do something cunning with the ordinal value, it would be much less obvious, and take more code - I don't think there'd be any benefit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With