开发者

Object expansion in functions calls

开发者 https://www.devze.com 2023-01-13 01:04 出处:网络
If I have a string like: String myColor =开发者_如何学C \"Color.RED\"; How do I get that to work in:

If I have a string like:

String myColor =开发者_如何学C "Color.RED";

How do I get that to work in:

graphics.setColor(myColor);

I guess I'm asking how do I pass a variable object name to a function. I've tried a bunch of stuff and can not get it working.


You'll need error checking to make sure the string is valid, but the crux of it is this:

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

Of course, you'll also have to use string manipulation to take the "Color." part out of the string.


There are some fancy, dirty tricks with the reflection API, but the easiest solution would be a map from Strings to the values:

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

and later on, when you need a color:

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


If you want write this in plain java, you must produce tons of code (using split by '.' ClassForName, getFields and so, so on...). Or you may use many bean helpers, i.e. BeanUtils, or get some examples from projects, already working with reflection (i.e. Apache Velocity)


Scecifically for enumerations (like the Color thing, but not only), see the [Enum.valueOf][1] method.

[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)


Can't really dereference a constant like that.

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

If you were to try and use the string you'd have 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 - don't.

0

精彩评论

暂无评论...
验证码 换一张
取 消