简体   繁体   English

Nonnull注释和标准java包

[英]Nonnull annotations and standard java packages

I'm trying to add findbugs-compatible annotations to a project, but noticed that @Nonnull is not always processed as I'd expect. 我正在尝试将findbugs兼容的注释添加到项目中,但注意到@Nonnull并不总是像我期望的那样处理。 For example findbugs does not assume that standard native collections can return null: 例如,findbugs不假设标准本机集合可以返回null:

void method(@Nonnull String bar) {...}

map = new HashMap();
method(map.get("foo"));

will pass the findbugs tests even though it shouldn't. 将通过findbugs测试,即使它不应该。 Can I configure findbugs somehow to make it alert in this case? 在这种情况下,我可以以某种方式配置findbugs以使其警报吗?

according to documentation, 根据文件,

The annotated element must not be null. 带注释的元素不能为null。 Annotated Fields must only not be null after construction has completed. 构造完成后,带注释的字段不能为空。 Annotated methods must have non-null return values. 带注释的方法必须具有非null返回值。

@Documented
@Target(value={FIELD,METHOD,PARAMETER,LOCAL_VARIABLE})
@Retention(value=CLASS)
@Nonnull(when=ALWAYS)
@TypeQualifierNickname
public @interface NonNull

or you can use @DefaultAnnotation(NonNull.class) on a class or package, and then use @Nullable only on those parameters, methods or fields that you want to allow to be null. 或者您可以在类或包上使用@DefaultAnnotation(NonNull.class),然后仅对要允许为null的那些参数,方法或字段使用@Nullable。

the analysis is done on source. 分析是在源头完成的。

so try this, it works for me 所以试试这个,它对我有用

/**
 * @param args
 */
public static void main(String[] args) {
    method( getValue());
}

private static void method(@NonNull Object obj){
    System.out.println(obj);
}

@CheckForNull
private static Object getValue(){
    Map map = new HashMap();
    return map.get("foo");
}

or you can try a Design By Contract using http://c4j.sourceforge.net/ 或者您可以使用http://c4j.s​​ourceforge.net/尝试设计合同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM