Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert one enum to another enum in java?

Tags:

java

enums

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?

like image 336
user710818 Avatar asked Jun 18 '12 05:06

user710818


People also ask

How do I assign one enum to another in Java?

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.

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.

Can enum be cloned?

The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.


1 Answers

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.

like image 77
Jon Skeet Avatar answered Sep 20 '22 21:09

Jon Skeet