Java properties - int becomes null

While I saw similar questions asked earlier, the accepted answers seemed to give an answer to another question (IMO).

I just joined the company, and before making any changes / corrections, I want all the tests to pass. I fixed everything but one, which I discovered due to some (for me) unexpected behavior in Java. If I insert a key / value pair into a Properties object, where the value is int, I expected autoboxing to come into play, and getProperty will return a string. However, this is not what happens (JDK1.6) - I get zero. I wrote 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 result of this:

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

In the "Properties" source code, I see the following:

 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 is not a line, it uses null. I see no reason why this behavior would be desirable / expected. The code was almost certainly written by someone more capable than me, so I guess there is a good reason for this. Can anyone explain? If I did something dumb, I’ll save time and just tell me that !:-)

Thank you very much

+4
source share
2 answers

This is the form of documents: "Because properties are inherited from Hashtable, the put and putAll methods can be applied to the Properties object. Their use is very discouraged because they allow the caller to insert records whose keys or values ​​are not strings. Instead, use the setProperty method. the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, a call to the propertyNames or list method will fail if it is called to "compromised" Properties object that contains nestrochny key. "

+2
source

I changed your code to use the setProperty method according to the docs and it causes a 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); } } 
0
source

All Articles