Eclipse Exceptional Parsing Throws False Positive NullPointerException
I am experimenting with Messages classes instead of using hard-coded strings for custom displays. However, I am getting a warning Potential null pointer access: this expression has a '@Nullable' type
from Eclipse (Luna - 4.4.1) with the following code:
In package-info.java:
/**
* My pacakge of tests.
*
* @author Flic
*/
@NonNullByDefault
package org.sample;
import org.eclipse.jdt.annotation.NonNullByDefault;
In Messages.java:
package org.sample;
import static java.util.ResourceBundle.getBundle;
import java.util.*;
import org.eclipse.jdt.annotation.Nullable;
public class Messages
{
private static final String BUNDLE_NAME = "org.sample.messages"; //$NON-NLS-1$
private static final @Nullable ResourceBundle RESOURCE_BUNDLE =
getBundle(BUNDLE_NAME);
private Messages()
{
}
public static @Nullable String getString(String key)
{
String msgVal = null;
try
{
if (RESOURCE_BUNDLE != null)
msgVal = RESOURCE_BUNDLE.getString(key); // Warning on RESOURCE_BUNDLE
}
catch (MissingResourceException mrEx)
{
msgVal = '!' + key + '!';
}
return msgVal;
}
}
The warning goes away if I copy the member variable to local and check instead:
public static @Nullable String getString(String key)
{
ResourceBundle checkBundle = RESOURCE_BUNDLE;
String msgVal = null;
try
{
if (checkBundle != null)
msgVal = checkBundle.getString(key); // No warning here
}
catch (MissingResourceException mrEx)
{
msgVal = '!' + key + '!';
}
return msgVal;
}
Can anyone explain why null checking a static final member variable is not enough to avoid a potential null pointer, but assigning its value to a local variable and checking that it is ok instead? Similar checks with String or Integer member variables are apparently specific to ResourceBundle objects.
+3
source to share