Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set fields with reflection - String has no valueOf(String) method

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.

like image 570
fabb Avatar asked May 30 '10 14:05

fabb


1 Answers

As you've noticed, there is no String.valueOf(String). However, I wouldn't consider your implementation a hack, just recognition of the minor inconsistency in the JDK classes.

For more robust String to Object conversion, you might consider using PropertyEditors, which directly support String to Object conversion - implementation for primitive types and Strings provided by default.) Your parse method will then be consistent, and extendible to handle different types. Better still are the conversion classes in Commons Convert, and Spring 3 Type Converters, as these are focused purely on conversion, and not GUI editing of properties.

like image 60
mdma Avatar answered Oct 08 '22 23:10

mdma