Sufiyan Ghori
Sufiyan Ghori

Reputation: 18753

How to access Array elements as constants - Java

I am trying to store the Color values in Java Array but I know that these values are stored as strings,

String[] colorarray = {"Color.yellow","Color.red","Color.blue"};

Now, I couldn't access this array element to set the color, i.e

g.setColor(colorarray[0]);

Because all the values in the array are strings. How could I convert these values to the constants ?

Upvotes: 0

Views: 147

Answers (3)

StormeHawke
StormeHawke

Reputation: 6207

If you have control over the array, by all means change it to just be an array of Colors as suggested by several other people.

Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};

If you don't have control over the array and you have to use it as-is, you'll need to do one of two things:

  1. Use reflection to access the static members of the Color class (a quick Google search will give you plenty of examples on how to do this so I won't go into it here)
  2. Create a Java 7 switch statement on the Strings to interpret each possible color value in the array into Color.XXX where XXX is the name of your color. (This could also be done using a big if-else block but that wouldn't be as clean)

One other quick note - variable names in Java are, by convention, in camelCase starting with a lower-case letter. This helps make your code more readable. (Class names are CamelCase, package names are lower.case)

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

Use

Color[] colorArray = {Color.YELLOW, Color.RED, Color.BLUE};

Upvotes: 11

Manish Tuteja
Manish Tuteja

Reputation: 205

Straightforward, use this :

Color[] colorarray = {Color.YELLOW, Color.RED, Color.BLUE};

Upvotes: 7

Related Questions