Getter and @Nonnull

I get a warning from an eclipse and I know that I can remove it with a warning about suppression, but I would rather understand what makes it a thing that can be null.

package-info.java

@ParametersAreNonnullByDefault package test; import javax.annotation.ParametersAreNonnullByDefault; 

test.java

 package test; public class Test { public static void main( final String[ ] args ) { System.out.println( new Test( "a" ).getS( ) ); } private final String s; public Test( final String s ) { this.s = s; } public String getS( ) { return this.s;//Null type safety: The expression of type String needs unchecked conversion to conform to '@Nonnull String' } } 

I do not understand why I get this warning ...

PS:

public Test( @Nonnull final String s ) { β†’ public Test( @Nonnull final String s ) { value annotations are redundant by default, which apply to this location

@Nonnull private final String s; β†’ nothing changes

+7
source share
1 answer

The problem is that the @Nonnull annotation does not affect the fields. It is supported only for:

  • Method Parameters
  • Method Return Values
  • Local variables (inside the code block)

See eclipse documentation

So it’s quite obvious - since Nonnull is not checked in the margins - the compiler does not know that Test.s is Nonnull and complains about it.

The obvious solution would be to add @SuppressWarnings ("null") in the access field (or in the method, if it's a simple getter):

 public String getS() { @SuppressWarnings("null") @Nonnull String s = this.s; return s; } 
+6
source

All Articles