2

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.

FoxVocs
  • 41
  • 5
  • 1
    How do you end up with a String as `Color.RED` for the [Color](https://docs.oracle.com/javase/7/docs/api/java/awt/Color.html) class. – João Dias Oct 22 '21 at 00:06
  • 1
    What code have you written while trying to solve your problem? Surely, you didn't ask this question without first trying, right? – MarsAtomic Oct 22 '21 at 00:07
  • All of the common calls I have tried ended up with different formats that can be translated between String and Color, as I had mentioned above. However, I cannot find any ways to do this with the specific String format of Color._____. It seems to be the only format I cannot find a way to translate between String and Color. – FoxVocs Oct 22 '21 at 00:23
  • Does this answer your question? "[Converting a String to Color in Java](https://stackoverflow.com/q/2854043/90527)", "[How can I convert string to const class int value?](https://stackoverflow.com/q/8952561/90527)" – outis Oct 22 '21 at 09:16

1 Answers1

1

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);
João Dias
  • 16,277
  • 6
  • 33
  • 45