bobbyrne01
bobbyrne01

Reputation: 6745

Calling getProperty on a Properties instance is returning null instead of value

Why is the code below returning null, instead of true?

I can see that the property is being set based on the {TEST=true} output.

Java code:

import java.util.Properties;

public class Test {

    public static void main(String[] args) {
        System.out.println("1");
        Properties props = new Properties();
        props.put("TEST", true);
        System.out.println(props);
        System.out.println(props.getProperty("TEST"));
        System.out.println("2");
    }
}

Program output:

1
{TEST=true}
null
2

Upvotes: 1

Views: 4398

Answers (3)

chaitanya dalvi
chaitanya dalvi

Reputation: 1669

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If 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, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

So for String use setProperty() and getProperty() method and for Object use put() and get() method.

Upvotes: 0

Riaan Nel
Riaan Nel

Reputation: 2535

Use setProperty() instead of put(). getProperty() and setProperty() operate on Strings. See the JavaDoc, here: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#setProperty-java.lang.String-java.lang.String-

If you look at the source code for the Properties class, you should see that it does an instanceof check on the value of the property that it retrieves in getProperty(). If the property value is not a String, it returns null.

Upvotes: 2

nullPointer
nullPointer

Reputation: 4574

The put method you use is taken from HashTable which Properties class is extending. If you want to use put then to retrieve it you should use get :

props.get("TEST");

However as mentioned in the comments, for setting properties you should be using setProperty() method instead :

props.setProperty("TEST", "true");

Upvotes: 1

Related Questions