不,@ParametersAreNonnullByDefault
仅适用于方法的参数——它从调用者接受的值(括号之间)。该方法仍然可以自由地返回一个null
值。
这是一个结合了您可以应用的所有三个位置的类@Nonnull
,尽管在我们的代码中我仍然使用三个单独的注释,其中一个由 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 {
}