Eclipse null type safety is wrong on return value

857 views Asked by At

Eclipse seems to do wrong analisys , method test1 is ok, but method test2 give the error:

Null type safety: The expression of type String needs unchecked conversion to conform to @NonNull

public class TestCase {
   public Object o;

  @NonNull
  public Object test1()  {
      Object local = new Object();
      return local;
  }

  @NonNull
  public Object test2()  {
      o = new Object();
      return o;
  }    
}
2

There are 2 answers

2
Jon Skeet On

I suspect the problem is that you're returning a value which may have been changed by a different thread. It is possible for that method to return a null reference, basically. You can avoid that by using a temporary variable:

@NonNull
public Object test2()  {
    Object tmp = new Object();
    o = tmp;
    return tmp;
}    
0
greg-449 On

In Eclipse 4.3 you can now use @NonNull on class members, so you can say

   @NonNull
   public Object o;

which will stop the warning - but you better be sure that the member is actually initialized!