如何使用 java 中的默认值构造属性列表?

how to construct properties list with defaults in java?

此代码:

import java.util.Properties;
public class P {
    public static void main(String[] args) {
        Properties defaultProperties=new Properties();
        defaultProperties.put("a",1);
        System.out.println("default: "+defaultProperties);
        Properties properties=new Properties(defaultProperties);
        System.out.println("other: "+properties);
    }
}

打印:

default: {a=1}
other: {}

在 eclipse luna 中使用 java 8。

应该如何构建具有默认值的属性列表?

您正在使用 defaultProperties.put() 而不是 defaultProperties.setProperty()。因此,您的 "a" 未被识别为 属性。

所以改用:

defaultProperties.setProperty("a", "1");

properties 对象仍将打印为空(这就是 new Properties(Properties defaults) 构造函数 is supposed to do!)但是如果您使用:

System.out.println(properties.getProperty("a"));

你会看到你得到“1”。

您的代码有 2 个问题。

  1. 当您使用 get()put() 时,默认属性不起作用。

您需要执行 setProperty() 和“getProperty()”。

  1. 当您打印属性文件时,它不会包含默认属性。 toString() 方法没有那么复杂。

改用这个:

Properties defaultProperties=new Properties();
defaultProperties.setProperty("a","s");
System.out.println("default: "+defaultProperties);
Properties properties=new Properties(defaultProperties);
System.out.println("other: "+properties.getProperty("a"));

您可以使用 put() 方法,但使用字符串作为值:

properties.put("a","1");

我知道签名是:Object java.util.Hashtable.put(Object key, Object value)

但是

public String getProperty(String key) {
    Object oval = super.get(key);
    String sval = (oval instanceof String) ? (String)oval : null;
    return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
}

如果值不是 String 类型,则此函数 returns 为 null。

A结尾:

Properties properties = new Properties();
properties.put("a" , "1");
System.out.println("default: "+properties);
Properties properties2 = new Properties( properties );
System.out.println("other: "+ properties2.getProperty( "a"  ) );