简体   繁体   中英

Eclipse null analysis raises false positive NullPointerException warning

I am experimenting with Messages classes instead of using hardcoded strings for user displays. However, I get a Potential null pointer access: this expression has a '@Nullable' type warning 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 a local and check that 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 the null check on the static final member variable is insufficient to avoid a potential null pointer but assigning its value to a local variable and checking that instead is OK? Similar checks against String or Integer member variables are fine - this seems to be specific to ResourceBundle objects.

It would appear this is a bug in Eclipse's nullness checker. Hopefully this will be addressed in later versions of Eclipse, but I will have a look at the Checker Framework as well. Thank you to those who have taken a look and made comments.

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