开发者

A reflection based Object binder for java.util.Properties?

开发者 https://www.devze.com 2023-03-15 14:32 出处:网络
I would like to automatically bind properties from a java.util.Properties instance to the fields in an object.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号