简体   繁体   中英

Java Properties - int becomes null

Whilst I've seen similar looking questions asked before, the accepted answers have seemingly provided an answer to a different question (IMO).

I have just joined a company and before I make any changes/fixes, I want to ensure that all the tests pass. I've fixed all but one, which I've discovered is due to some (to me) unexpected behavior in Java. If I insert a key/value pair into a Properties object where the value is an int, I expected autoboxing to come into play and getProperty would return a string. However, that's not what's occuring (JDK1.6) - I get a null. I have written a test class below:

import java.util.*;

public class hacking
{
    public static void main(String[] args)
    {
        Properties p = new Properties();
        p.put("key 1", 1);
        p.put("key 2", "1");

        String s;

        s = p.getProperty("key 1");
        System.err.println("First key: " + s);

        s = p.getProperty("key 2");
        System.err.println("Second key: " + s);
    }
}

And the output of this is:

C:\Development\hacking>java hacking
First key: null
Second key: 1

Looking in the Properties source code, I see this:

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

The offending line is the second line - if it's not a String, it uses null. I can't see any reason why this behavior would be desired/expected. The code was written by almost certainly someone more capable than I am, so I assume there is a good reason for it. Could anyone explain? If I've done something dumb, save time and just tell me that! :-)

Many thanks

这是表单文档:“因为Properties从Hashtable继承,所以put和putAll方法可以应用于Properties对象。强烈建议不要使用它们,因为它们允许调用方插入键或值不是String的条目。setProperty方法应该如果在包含非字符串键或值的“受损” Properties对象上调用store或save方法,则调用将失败;类似地,如果调用propertyNames或list方法,则调用将失败在包含非字符串键的“受损”属性对象上。

I modified your code to use the setProperty method as per the docs and it brings up compilation error

package com.stackoverflow.framework;
import java.util.*;

public class hacking
{
    public static void main(String[] args)
    {
        Properties p = new Properties();
        p.setProperty("key 1", 1);
        p.setProperty("key 2", "1");

        String s;

        s = p.getProperty("key 1");
        System.err.println("First key: " + s);

        s = p.getProperty("key 2");
        System.err.println("Second key: " + s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM