如何在给定键/值映射的情况下设置对象的字段?

时间:2010-09-20 01:29:16

标签: java spring

我想在spring中实现类似于JobDetailBean的东西

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html#scheduling-quartz-jobdetail

可以将属性映射应用于对象以设置其字段。

我查看了弹簧源代码,但看不到他们是如何做到的。

有人对如何做到这一点有任何想法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用Spring的DataBinder

答案 1 :(得分:1)

这是一个没有任何Spring Dependencies的方法。您将bean对象和属性名称Map提供给属性值。它使用JavaBeans introspector机制,因此它应该接近Sun标准:

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);
    }
}

<强>参考:

答案 2 :(得分:0)

几乎可以肯定,这是使用反射API的元素完成的。 Bean具有可通过表单

的功能设置的字段
"set"+FieldName 

字段的第一个字母大写。

这是另一个按字符串名称调用方法的SO帖子:How do I invoke a Java method when given the method name as a string?

相关问题