A reflection based Object binder for java.util.Properties?
I would like to automatically bind properties from a java.util.Properties
instance to the fields in an object.
Preferable something like this:
Properties props = ... // has for instance the property "url=http://localhost:8080
MyType myType = ...
PropertiesBinder.bind(props,开发者_如何学Go myType);
assertEquals("http://localhost:8080", myType.getUrl());
It is not that hard to roll your own, but i wonder if someone already has done this?
BeanUtils.populate(object, map)
Properties extends Hashtable implements Map
, so you can use it in the above method.
If you just want to set String values, this will do (you do not need a third party library):
public static void bind(Properties props, Object obj) throws Exception {
Field field;
Class<?> cLass = obj.getClass();
for (String prop : props.stringPropertyNames()) {
try {
field = cLass.getDeclaredField(prop);
if (field.getType().equals(String.class)) {
if (!field.isAccessible())
field.setAccessible(true);
field.set(obj, props.get(prop));
}
} catch (NoSuchFieldException e) {
System.err.println("no luck");
}
}
}
For advanced things, I'd suggest the preferences API, guice, spring, pico container, or a tool that I maintain by name InPUT.
If you are doing configuration type things, take a look at config-magic which allows you to use annotations to map configuration properties to bean getters.
Property Binder: http://pholser.github.com/property-binder
精彩评论