سؤال

In a ListResourceBundle implementation I define an array with some keys containing null values. It compiles fine the loading process of the bundle containing a null value. However when I call getObject on a key with a non-null value (like in the following example "Pollution" which has value "high"), it gives me a NullPointerException.

Do you have an idea why it happens in that way?

ResourceBundle labels = ResourceBundle.getBundle("bundlething", new Locale("it"));
labels.getObject("Pollution");// here NullPointerException, However Pollution has a \n

value, other keys of the same array do not.

UPDATE: This is the stacktrace I receive:

Exception in thread "main" java.lang.NullPointerException at java.util.ListResourceBundle.loadLookup(ListResourceBundle.java:196) at java.util.ListResourceBundle.handleGetObject(ListResourceBundle.java:124) at java.util.ResourceBundle.getObject(ResourceBundle.java:387) at ResourceBundleThing.main(ResourceBundleThing.java:38)

and this is the bundle I load by passing new Locale("it") as target Locale:

import java.util.ListResourceBundle;
public class bundlething_it extends ListResourceBundle {

    private  Object [][] contents  ={{"Inhabitants",null},{"Pollution",new Double(3.4034)},{"Lollerball",new Integer(132)}};
    public Object[][] getContents()
    {
        return contents;
    }

}

There is null corresponding to "Inhabitans" however I am referring only to "Pollution" which has a non-null value. Still I get a NullPointerException; If I remove that null from "Inhabitants" it works.. so it's there the problem, I know. However I would like to know why since I am not using that particular key-value pair. Does it load all the values as soon as getObject it's called?

Thanks in advance.

هل كانت مفيدة؟

المحلول

The stack trace precisely indicates where the error comes from:

    Object[][] contents = getContents();
    HashMap<String,Object> temp = new HashMap<>(contents.length);
    for (int i = 0; i < contents.length; ++i) {
        // key must be non-null String, value must be non-null
        String key = (String) contents[i][0];
        Object value = contents[i][1];
        if (key == null || value == null) {
            throw new NullPointerException(); // <-- HERE
        }
        temp.put(key, value);
    }

So, you have your answer: although I haven't seen it mentioned in the documentation, ListResourceBundle doesn't allow null values.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top