有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在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: {}

在EclipseLuna中使用Java8

人们应该如何构造一个带有默认值的属性列表


共 (2) 个答案

  1. # 1 楼答案

    可以使用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类型,则此函数返回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"  ) );
    
  2. # 2 楼答案

    您正在使用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”