Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a Java method as "must use result" for static analysis purposes?

When using GCC to compile C or C++, you can mark functions with attribute((warn_unused_result)) which will cause the compiler to complain if you invoke a function that returns something and then don't assign it to anything.

I have some methods in a Java library I develop that have methods like this - calling them and then throwing away the result is always a bug. I would like API users to be able to identify such bugs via static analysis, such as with FindBugs or IntelliJ inspections.

I am wondering if there is a method annotation that is commonly used to mark methods or functions as "must use result". FindBugs has some special case bug-finders for the standard library, but a general way would be useful.

like image 689
Mike Hearn Avatar asked May 06 '13 09:05

Mike Hearn


2 Answers

There is totally a standard annotation for this, and it is @CheckReturnValue. FindBugs has it; see e.g. here.

Guava uses it internally -- e.g. in the configuration methods for Splitter -- from JSR 305.

like image 121
Louis Wasserman Avatar answered Oct 18 '22 08:10

Louis Wasserman


Use

import javax.annotation.CheckReturnValue;
.
.
.
@CheckReturnValue

Some good examples of @CheckReturnValue are available on the Google error-prone project wiki. (If you like static analysis tools such as FindBugs, you should definitely check out error-prone; it works on the source/AST rather than the bytecode, which makes it complementary to tools such as FindBugs.)

like image 26
Timothy Woods Avatar answered Oct 18 '22 08:10

Timothy Woods