0

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 ?

Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
Anthony
  • 1,637
  • 4
  • 21
  • 29
  • Spring most likely uses setter and getter methods that it finds on the object using reflection, or uses reflection to set the fields directly. If the property name is "foo" then it looks for setFoo() or the foo field to set directly. See this page about reflection: http://java.sun.com/developer/technicalArticles/ALT/Reflection/ – Gray Sep 20 '10 at 01:40
  • JobDetailBean extends JobDetail from Quartz so all properties through setter and getter are available to JobDetailBean. I am not sure what is your question. – Jaydeep Patel Sep 20 '10 at 10:42

3 Answers3

1

You can use Spring's DataBinder.

axtavt
  • 228,184
  • 37
  • 489
  • 472
1

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:

Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
0

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?

Community
  • 1
  • 1
Mark Elliot
  • 68,728
  • 18
  • 135
  • 157