哪个Java库允许我初始化对象';从属性文件中删除属性?
是否有Java库可以让您将属性文件直接“反序列化”到对象实例中 示例:假设您有一个名为init.properties的文件:哪个Java库允许我初始化对象';从属性文件中删除属性?,java,Java,是否有Java库可以让您将属性文件直接“反序列化”到对象实例中 示例:假设您有一个名为init.properties的文件: username=fisk password=frosk class Connection { private String username; private String password; public void setUsername(String username) { this.username = usernam
username=fisk
password=frosk
class Connection {
private String username;
private String password;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
以及一个具有某些属性的Java类:
username=fisk
password=frosk
class Connection {
private String username;
private String password;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
我想这样做:
Connection c = MagicConfigurator.configure("init.properties", new Connection())
并让MagicConfigurator将属性文件中的所有值应用于连接实例
有这样一个类的库吗?我会看一看,看看是否存在使用它的等价物。只有部分答案:查找第一部分的。有一些方法可以加载/存储
我记不清了,但我在某处读到一些关于这门课的讨论,说这门课的设计很有趣。它特别继承了
哈希表
,但严格来说,它的行为不像哈希表
。我不记得有什么争论,但我认为这是因为在这种情况下,is-a关系并不真正正确 图书馆?这只是几行代码:
对于每把钥匙:
您甚至可以将其添加到配置类中,并实现一个读取属性对象的构造函数。使用它非常简单。该库甚至负责类型转换。此外,您甚至可以设置嵌套对象和数组的属性
public static void setProperties(Object bean, Properties properties) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
for (Map.Entry<Object, Object> e : properties.entrySet()) {
if (e.getKey() instanceof String) {
BeanUtils.setProperty(bean, (String) e.getKey(), e.getValue());
}
}
}
钥匙和年龄会动态转换为数字。但是,密钥数组必须提前创建,Person也是如此。我要说的是,自己做就行了(正如Andreas_D所建议的那样),这真的很简单,唯一“困难”的部分是进行类型转换 但是如果您真的想使用库来实现这一点,您可能会发现OGNL中强大的表达式语法非常有用
stack.setValue(“property”,value);
)额外的好处是,您也可以使用完整的OGNL语法访问组件对象的属性。您可以执行类似于
stack.setValue(“property.name”,value)的操作
其中有一个getProperty()
返回并使用get/setName()
方法创建对象 如果使用xml而不是属性,则可以使用JaxB。使用内省类BeanInfo来实现这一点非常简单
e、 它的核心应该是这样的
public void readProperties(Object o, Properties p) throws IntrospectionException, InvocationTargetException, IllegalAccessException
{
BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors())
{
String value = p.getProperty(propertyDescriptor.getName());
if ( value != null && propertyDescriptor.getWriteMethod() != null )
{
propertyDescriptor.getWriteMethod().invoke(o, value);
}
}
}
我会用这个当然,我可以自己写,但是如果已经有一个标准的解决方案我可以重用,我就不麻烦了。