I want to enumerate colors and use Color instances. Therefore I have created an
enum with a private field and a get-function, but using it is cumbersome because
of the need to call getColor()
.
Is there a better approach at directly using the enumeration constant without calling getColor()
?
public class ColorListTest {
public enum ColorList
{
WHITE(new Color(255, 255, 255)),
BLACK(new Color(255, 255, 255)),
;
private Color color;
private ColorList(Color color) { this.color = color; }
public Color getColor() { return color; }
}
public static void main(String[] args)
{
Color color = ColorList.WHITE.getColor();
// I'd rather have something similar to:
// Color color = WHITE;
// Color color = ColorList.WHITE;
}
}
The answer to Using enums as key for map question suggests to use a map, which also needs to call get().
Another option is to use a list of constants, which is less type safe since there is no enum anymore:
static public class ColorList
{
static final Color WHITE = new Color(null, 255, 255, 255);
static final Color BLACK = new Color(null, 0, 0, 0);
}
(The other posts I found seem to deal with string conversions a lot.)
So do you have a recommendation on a nice to use enum?