How to create a list of properties with default values ​​in java?

this code:

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);
    }
}

      

prints:

default: {a=1}
other: {}

      

using java 8 in eclipse luna.

How do I create a list of properties with default values?

+3


source to share


3 answers


These are 2 problems with your code.

  • The default properties don't work if you use get()

    and put()

    .

Instead, you need to execute setProperty()

'getProperty ()' as well.



  1. When you print a properties file, it will not include properties by default. The method is toString()

    not that optimized.

Use this instead:

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"));

      

+3


source


You are using defaultProperties.put()

instead defaultProperties.setProperty()

. Therefore your "a" is not recognized as a property.

So use instead:

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

      



The object properties

will still print blank (which is what the constructor should do new Properties(Properties defaults)

!), But if you use

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

      

You will see that you have received a "1".

+3


source


You can use the put () method, but with a String as value:  properties.put("a","1");

I know the signature is: Object java.util.Hashtable.put(Object key, Object value)

But with 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; }

If the value is not a String, this function returns null.

A end:

        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"  ) );

      

0


source







All Articles