开发者

Is @ParametersAreNonnullByDefault applies to method return values too?

The documentation for @ParametersAreNonnullByDefault says, that:

This annotation can be applied to a package, class or method to indicate that the method parameters in that element are nonnull by default unless ...

I don't consider a method's return type/value to be it's parameter. It is only part of its signature, so this is kind of ambiguous for me.

The Java tutorial for methods seems to think like me.


As Joachim Sauer pointed out for me in the comments section of开发者_JAVA技巧 his answer, the name @ParametersAreNonnullByDefault (parameters) should've clearly indicated for me that this annotation doesn't apply to methods' return types/values. I was blind! :) Thanks Joachim!

In light of this I can only says that an @EverythingIsNonnullByDefault should exist somwhere. :)


No, @ParametersAreNonnullByDefault applies only to a method's parameters--the values it accepts from the caller (between the parentheses). The method is still free to return a null value.

Here's a class that combines all three places where you can apply @Nonnull, though in our code I still use three separate annotations, one of which is supplied by JSR-305.

package com.sample;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.annotation.meta.TypeQualifierDefault;

/**
 * This annotation can be applied to a package, class or method to indicate that all
 * class fields and method parameters and return values in that element are nonnull 
 * by default unless overridden.
 */
@Documented
@Nonnull
@TypeQualifierDefault({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EverythingIsNonnullByDefault {
}


I don't see a reason why @ParametersAreNonnullByDefault should apply to return values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜