如何解决java.util.Properties的基于反射的对象绑定器?
| 我想将属性从“ 0”实例自动绑定到对象中的字段。 最好是这样的:Properties props = ... // has for instance the property \"url=http://localhost:8080
MyType myType = ...
PropertiesBinder.bind(props,myType);
assertEquals(\"http://localhost:8080\",myType.getUrl());
推出自己的游戏并不难,但是我想知道是否有人已经这样做了?
解决方法
BeanUtils.populate(object,map)
Properties extends Hashtable implements Map
,因此可以按上述方法使用。
, 如果您只想设置String值,则可以这样做(您不需要第三方库):
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\");
}
}
}
对于高级内容,我建议使用偏好API,guice,spring,pico容器或我通过名称InPUT维护的工具。
, 如果您正在做配置类型的事情,请看一下config-magic,它允许您使用批注将配置属性映射到bean getter。
, 属性绑定器:http://pholser.github.com/property-binder
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。