viraptor
viraptor

Reputation: 34185

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?

Upvotes: 5

Views: 4270

Answers (1)

zudokod
zudokod

Reputation: 4094

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/

Upvotes: 2

Related Questions