Extending Objects in Function Calls

If I have a line like:

String myColor = "Color.RED"; 

How do I get to work:

 graphics.setColor(myColor); 

I think I'm asking how to pass a variable name to a function. I tried a bunch of things and can't make it work.

+4
source share
5 answers

You will need error checking to make sure the string is correct, but most importantly:

  graphics.setColor ((Color) Color.class.getField ("RED"). get (null));

Of course, you will also have to use string manipulations to take Color. part of the string.

+3
source

There are some fancy, dirty tricks with the reflection API, but the simplest solution would be a line map for the values:

 Map<String, Color> colorMap = new HashMap<String, Color>(); colorMap.put("Color.RED", Color.RED); 

and then when you need color:

 String myColor = "Color.RED"; graphics.setColor(colorMap.get(myColor)); 
+2
source

If you want to write this in plain Java, you have to create tons of code (using split by .. ClassForName, getFields and so on). Or you can use many bean helpers, i.e. BeanUtils , or get examples from projects already working with reflection (i.e. Apache speed )

0
source

It is impossible to find such a constant.

Use Color.getColor("Color.RED".split("\.")[1]) to get the same.

If you try to use a string, you will need to do something like:

 String[] parts = myColor.split("\."); String className = parts[0]; String fieldName = parts[1]; Class c = Class.forName(className); Field f = c.getField(fieldName); Object o = f.get(null); Color col = (Color) o; 

In conclusion - do not.

-1
source

Specifically for enumerations (for example, the Color property, but not only), see the [Enum.valueOf] method [1].

[1]: http://cupi2.uniandes.edu.co/~cupi2/sitio/images/recursos/javadoc/j2se/1.5.0/docs/api/java/lang/Enum.html#valueOf(java.lang .Class , java.lang.String)

-1
source

All Articles