Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. For example findbugs does not assume that standard native collections can return null:

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

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

will pass the findbugs tests even though it shouldn't. Can I configure findbugs somehow to make it alert in this case?

like image 672
viraptor Avatar asked Nov 05 '22 23:11

viraptor


1 Answers

according to documentation,

The annotated element must not be null. Annotated Fields must only not be null after construction has completed. Annotated methods must have non-null return values.

@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.

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/

like image 138
zudokod Avatar answered Nov 09 '22 13:11

zudokod