How do I mark a Java method as "should use the result" for static analysis purposes?

When using GCC to compile C or C ++, you can mark functions using the ((warn_unused_result)) attribute , which is why the compiler will complain if you call a function that returns something and then doesn't execute, assign it something- sometime.

I have some methods in the Java library that I am developing that have methods that call and then discard the result is always an error. I would like API users to be able to identify such errors through static analysis, for example using FindBugs or IntelliJ checks.

I am wondering if there is a method annotation that is commonly used to designate methods or functions as "should use the result." FindBugs has some special error finders for the standard library, but a general way would be helpful.

+4
source share
2 answers

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

Guava uses it internally - for example. in configuration methods for Splitter - from JSR 305 .

+3
source

Using

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

Some good examples of @CheckReturnValue are available on the Google Project Victorian Wiki . (If you like static analysis tools like FindBugs, you should definitely check for error-prone , it works with the / AST source, not the bytecode, which makes it a complement to tools like FindBugs.)

0
source

Source: https://habr.com/ru/post/1479330/


All Articles