Set fields with instrospection - Problem with String.valueOf(String)
Posted
by fabb
on Stack Overflow
See other posts from Stack Overflow
or by fabb
Published on 2010-05-30T14:12:17Z
Indexed on
2010/05/30
14:22 UTC
Read the original article
Hit count: 341
Hey there!
I'm setting public fields of the Object 'this' via reflection. Both the field name and the value are given as String. I use several various field types: Boolean, Integer, Float, Double, an own enum, and a String. It works with all of them except with a String. The exception that gets thrown is that no method with the Signature String.valueOf(String) exists... Now I use a dirty instanceof workaround to detect if each field is a String and in that case just copy the value to the field.
private void setField(String field, String value) throws Exception {
Field wField = this.getClass().getField(field);
if(wField.get(this) instanceof String){ //TODO dirrrrty hack
//stupid workaround as java.lang.String.valueOf(java.lang.String) fails...
wField.set(this, value);
}else{
Method parseMethod = wField.getType().getMethod("valueOf", new Class[]{String.class});
wField.set(this, parseMethod.invoke(wField, value));
}
}
Any ideas how to avoid that workaround?
Do you think java.lang.String should support the method valueOf(String)?
thanks,
fabb
© Stack Overflow or respective owner