Bean Wrapper and the Property Editor

Lets say you have

Person{
 String name;
 boolean alive;
}

and I give you name=Bruce&alive=Yes

first you would split the above string and get the values.
so now you have something like
String attributeName = “name”;
String attributeValue = “Bruce”;

approach 1> the dirty approach

if("name".equals(attributeName )){
 person.setName(attributeValue );
}

of course you know why this is dirty…
if you have 10 attributes …you’ll end up with 10 if-else 😦

approach 2> Cleaner but not elegant

String methodName = "set"+attributeName;
Method m = person.getClass().getMethod(methodName, String.class);
m.invoke(person, attributeValue );

I will come back to why it is not elegant..

approach 3> Bean Wrapper

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
...

BeanWrapper wrapper = new BeanWrapperImpl(person);
wrapper.setPropertyValue(field, value); // that is all :)

Yes coming back to why approach 2 is not elegant is..
what about the 2nd attribute of person.. alive=Yes
You have to determine that alive is a boolean, either by reflection or again have if else in your code.
even if you do you still need to convert Yes to true.

BeanWrapper by default (as it loads) registers Spring provided property editors, which includes CustomBooleanEditor so approach 3 would work without any extra code.

Now lets say you have another property
boolean chromosome; //true false to be represented as “XX” and “YY” on the screen.

BeanWrapper wrapper = new BeanWrapperImpl(person);
CustomBooleanEditor booleanEditor =  new CustomBooleanEditor("XX", "YY", false);
wrapper.registerCustomEditor(boolean.class, "chromosome", booleanEditor);
wrapper.setPropertyValue(field, value);

you can find a bit more info at the below URL
http://static.springsource.org/spring/docs/2.0.x/reference/validation.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s