2

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

Matt Clark
  • 27,671
  • 19
  • 68
  • 123

2 Answers2

6

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;
    }
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
1

You can do this like this:

try {
        Class color=Class.forName("android.graphics.Color");
        Field field=color.getField("BLUE");
        int blue=field.getInt(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
wngxao
  • 72
  • 5
  • Sorry if I was uncler, the final output needs to be of a Color object. I thought of using _class.forName_ but was unsure how here. – Matt Clark Feb 29 '16 at 06:00
  • Nothing in the question suggest Android. I'd swap `android.graphics` for `java.awt`. Also, as OP wants the object. I'd use `Color blue = field.get(null);`. – Sarvadi Feb 29 '16 at 06:00
  • In java: try { Class color=Class.forName("java.awt.Color"); Field field=color.getField("blue"); Color blue=(Color) field.get(null); } catch (Exception e) { e.printStackTrace(); } – wngxao Feb 29 '16 at 06:04