Reputation: 1685
I want to implement something similar to the JobDetailBean in spring
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 ?
Upvotes: 0
Views: 904
Reputation: 298938
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:
Upvotes: 1
Reputation: 77054
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?
Upvotes: 0