Converting between a specific String and Color

Viewed 71

If given a String specifically in the format "Color.RED", "Color.BLUE", "Color.GREEN", etc. How can I convert these into the Color Object equivalents, and from Color Objects to Strings of the same format? I have seen how to translate to and from Integers and rgb code, but not this format.

1 Answers

You might need to use reflection on this one. Try the following:

String value = "Color.RED";
String colorId = value.replace("Color.", "");
Field field = Color.class.getField(colorId);
Color color = (Color) field.get(null);
Related