@Nullable Annotation Usage

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Using @Nullable in Java

Due to the inherent complexity, flow analysis is best performed in small chunks. Analyzing one method at a time can be done with good tool performance - whereas whole-system analysis is out of scope for the Eclipse Java compiler. The advantage is: analysis is fast and can be done incrementally such that the compiler can warn you directly as you type. The down-side: the analysis can not "see" which values (null or non-null) are flowing between methods (as parameters and return values).

This is where null annotations come into play. By specifying a method parameter as @NonNull you can tell the compiler that you don't want a null value in this position.

Reference

Reference 2

Usage:
This link explains what annotation to use where.

Usage 2

Getters/Setters: Yes, it is possible. The Project Lombok (http://projectlombok.org/index.html) defines annotations for generating getters/setters and more.

So for example

@lombok.Data;
public class Person {
private final String name;
private int age;
}

Will generate getter for name (not setter since it is final) and getter/setter for age. It will also generate equals, hashCode, toString and construtor initializing required fields (name). Adding @AllArgsConstructor would generate constructor initializing both fields.

There are other annotations and parameters giving you control over access rights (should your getter be protected or public), names (getName or name?), etc. And there is more. For example, I really like the extension methods.

Lombok is very easy to use. Just download the jar and use the annotations, then the getter/setters can be used in your code without actually being spelled out. Moreover, IDE's like Netbeans support this, so that you see the getter/setter in code completion, navigation, etc. The annotations are used only during compilation not during runtime, so you don't distribute lombok with your jar's.

NotNull: This is supported by findbugs and IdeaJ IDE, maybe others

Reference 3

What's the meaning of java.util.@Nullable?

The line public static <T> java.util.@Nullable Optional<T> toJavaUtil is written like this, because the usual style public static <T> @Nullable java.util.Optional<T> toJavaUtil is invalid. This is defined in the JLS §9.7.4:

It is a compile-time error if an annotation of type T applies to a type (or any part of a type) in a type context, and T is applicable in type contexts, and the annotation is not admissible.

For example, assume an annotation type TA which is meta-annotated with just @Target(ElementType.TYPE_USE). The terms @TA java.lang.Object and java.@TA lang.Object are illegal because the simple name to which @TA is closest is classified as a package name. On the other hand, java.lang.@TA Object is legal.

The type declaration of org.checkerframework.checker.nullness.qual@Nullable is:

@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})

So it is applying to this rule.

That this structure doesn't break the execution, since package java.util and class name Optional were split, can be seen when we look at the compiled code using javap -c [compiled class name]:

class just.a.test.Main {
just.a.test.Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static <T> java.util.Optional<T> toJavaUtil(blub.Optional<T>);
Code:
0: aload_0
1: ifnonnull 8
4: aconst_null
5: goto 12
8: aload_0
9: invokevirtual #2 // Method blub/Optional.toJavaUtil:()Ljava/util/Optional;
12: areturn
}

(blub.Optional is a local class where I copied the Guava code in, in order to get a minimal example to de-/compile)

As you can see, the annotation doesn't exist there anymore. It is only a marker for the compiler to prevent a warning when the method returns null (and a hint for the source code readers), but it won't be included in the compiled code.


This compiler error also applies to variables like:

private @Nullable2 java.util.Optional<?> o;

But can become acceptable when the annotation additionally gets the target type ElementType.FIELD, as written in the same JLS clause:

If TA is additionally meta-annotated with @Target(ElementType.FIELD), then the term @TA java.lang.Object is legal in locations which are both declaration and type contexts, such as a field declaration @TA java.lang.Object f;. Here, @TA is deemed to apply to the declaration of f (and not to the type java.lang.Object) because TA is applicable in the field declaration context.

javax.annotation: @Nullable vs @CheckForNull

I think it is pretty clear from the link you added: if you use @CheckForNull and the code that uses the value does not check for null, FindBugs will show it as an error.

FindBugs will ignore @Nullable.

In practice this annotation is useful only for overriding an overarching NonNull annotation.

Use @CheckForNull in the cases when the value must always be checked. Use @Nullable where null might be OK.

EDIT: it seems that @CheckForNull is not well supported at the moment, so I suggest avoiding it and using @NonNull (also see Which @NotNull Java annotation should I use?).
Another idea would be to get in touch directly with the FindBugs developers, and ask their opinion about the inconsistency in the documentation.

In which cases I should use @Nullable annotation?

It is in here.

javax.annotation.Nullable

I think you need this jar: jsr305.jar.

See also:

https://jcp.org/en/jsr/detail?id=305

http://jsr-305.googlecode.com/svn/trunk/javadoc/javax/annotation/package-tree.html

Regarding when you should use it - check this link.

@Nullable annotation usage

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}

You can use:

public void setX(@NotNull final Object aX ) {
// some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

Use of nullable in onCreateView and onCreatedView

The @Nullable annotation indicates a variable, parameter, or return value that can be null You ever get a "NullPointerException"? That's because the value is null.

Integer x; 

'x' Will be null because you haven't assigned a value to it so there will be errors using it. But what if you have a variable that might actually be null in some use cases? Well, you'd use the @Nullable annotation meaning that it's okay to be null.

@Nullable Bundle savedInstanceState

Bundle in this case might have nothing stored in it. So it's okay to be null when the method is called.

Same goes for the method onCreateView() meaning that the return can be null



Related Topics



Leave a reply



Submit