tags:

views:

44

answers:

3

I want to implement something similar to the JobDetailBean in spring

http://static.springsource.org/spring/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 ?

A: 

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: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string

Mark E
I'm guessing the code to do this already exists in the spring framework. I was hoping to just use that rather than roll my own.
Anthony
@Anthony: nothing I've cited uses anything Spring related.
Mark E
A: 

You can use Spring's DataBinder.

axtavt
A: 

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:

seanizer