Matt Clark Matt Clark - 6 months ago 40
Java Question

getting a color by name in java

I am working with an object model that contains a

Color
object.

import java.awt.Color;

public class MyObject {

...
private String color;

public void setColor( Color c ) ...
public Color getColor() ...
...

}


In the response of a json query, I am left with a physical name of a color


"color":"blue"


I know that the Color object has statics i.e.

Color.blue;


Is there any way to decode actual color names into Color objects? Or would I need to manually map the strings to rgb values myself?

I am looking for something that should be the output of this

Color c = new Color("blue");


which does not work

Answer

If your names correspond to those of Java's constants, you can use reflection to map them:

public static Color getColorByName(String name) {
    try {
        return (Color)Color.class.getField(name.toUpperCase()).get(null);
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
        return null;
    }
}