如何合并两个 java.util.Properties 对象? [英] How to merge two java.util.Properties objects?

查看:63
本文介绍了如何合并两个 java.util.Properties 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的类中有一个默认的 java.util.Properties 对象,以及它接受的默认属性,并让开发人员通过指定另一个 java 来覆盖其中的一些.util.Properties 对象,但我找不到这样做的好方法.

I'm trying to have a default java.util.Properties object in my class, with the default properties it accepts, and let the developer override some of them by specifying another java.util.Properties object, but I couldn't find a nice way for doing that.

预期用途如下:

Properties defaultProperties = new Properties();
defaultProperties.put("key1", "value1");
defaultProperties.put("key2", "value2");

Properties otherProperties = new Properties();
otherProperties.put("key2", "value3");

Properties finalProperties = new Properties(defaultProperties);

//
// I'd expect to have something like:
// 
// finalProperties.merge(otherProperties);
//

推荐答案

java.util.Properties 实现了 java.util.Map 接口,所以你可以就这样对待它,并使用putAll之类的方法来添加另一个Map的内容.

java.util.Properties implements the java.util.Map interface, and so you can just treat it as such, and use methods like putAll to add the contents of another Map.

然而,如果你把它当成一张地图,你需要非常小心:

However, if you treat it like a Map, you need to be very careful with this:

new Properties(defaultProperties);

这通常会引起人们的注意,因为它看起来像一个复制构造函数,但它不是.如果您使用该构造函数,然后调用类似 keySet()(继承自其 Hashtable 超类)之类的东西,您将得到一个空集,因为 MapProperties 方法不考虑您传递给构造函数的默认 Properties 对象.仅当您使用 Properties 本身中定义的方法(例如 getPropertypropertyNames 等)时,才会识别默认值.

This often catches people out, because it looks like a copy constructor, but it isn't. If you use that constructor, and then call something like keySet() (inherited from its Hashtable superclass), you'll get an empty set, because the Map methods of Properties do not take account of the default Properties object that you passed into the constructor. The defaults are only recognised if you use the methods defined in Properties itself, such as getProperty and propertyNames, among others.

所以如果你需要合并两个 Properties 对象,这样做更安全:

So if you need to merge two Properties objects, it is safer to do this:

Properties merged = new Properties();
merged.putAll(properties1);
merged.putAll(properties2);

这将为您提供更可预测的结果,而不是随意将其中一个标记为默认"属性集.

This will give you more predictable results, rather than arbitrarily labelling one of them as the "default" property set.

通常,我不建议将 Properties 视为 Map,因为(在我看来)这是 Java 早期的一个实现错误(Properties 应该有包含一个 Hashtable,而不是扩展它 - 那是一种懒惰的设计),但是 Properties 中定义的贫血接口本身并没有给我们很多选择.

Normally, I would recommend not treating Properties as a Map, because that was (in my opinion) an implementation mistake from the early days of Java (Properties should have contained a Hashtable, not extended it - that was lazy design), but the anemic interface defined in Properties itself doesn't give us many options.

这篇关于如何合并两个 java.util.Properties 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆