How to set the fields of an object given a map of key/values?
I want to implement something similar to the JobDetailBean in spring
http://static.springsource.org/spr开发者_运维技巧ing/docs/3.0.x/spring-framework-reference/html/scheduling.html#scheduling-quartz-jobdetail
where a map of properties can be applied to an object to set its fields.
I looked through the spring source code but couldn't see how they do it.
Does anybody have any ideas on how to do this ?
You can use Spring's DataBinder
.
Here is a method without any Spring Dependencies. You supply a bean object and a Map of property names to property values. It uses the JavaBeans introspector mechanism, so it should be close to Sun standards :
public static void assignProperties(
final Object bean,
final Map<String, Object> properties
){
try{
final BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
for(final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()){
final String propName = descriptor.getName();
if(properties.containsKey(propName)){
descriptor.getWriteMethod().invoke(
bean,
properties.get(propName)
);
}
}
} catch(final IntrospectionException e){
// Bean introspection failed
throw new IllegalStateException(e);
} catch(final IllegalArgumentException e){
// bad method parameters
throw new IllegalStateException(e);
} catch(final IllegalAccessException e){
// method not accessible
throw new IllegalStateException(e);
} catch(final InvocationTargetException e){
// method throws an exception
throw new IllegalStateException(e);
}
}
Reference:
- Introspector (Sun Java Tutorial)
- BeanInfo (javadoc)
- Introspector (javadoc)
Almost surely this is done using elements of the reflection API. Beans have fields that are settable via functions of the form
"set"+FieldName
where the field's first letter is capitalized.
Here's another SO post for invoking methods by a String name: How do I invoke a Java method when given the method name as a string?
精彩评论