How to enforce static imports for some methods using checkstyle?

1.1k views Asked by At

How to enforce static imports for some methods using checkstyle?

For example

I want the following method to be used only from static import:

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

So code like this shouldn't be allowed:

if (Objects.nonNull(varName)) {

Any ideas how to achieve that with (preferably) standard or non standard tools?

2

There are 2 answers

0
tkruse On BEST ANSWER

You could forbid the String that imports Objects:

<module name="RegexpSinglelineJava">
    <!-- Please statically import methods -->
    <property name="format" value="import java.util.Objects;"/>
</module>
0
IgorZep On

Pease! Never use static import for Objects.isNull / Objects.nonNull... Not because static imports are bad. But the use of isNull() / nonNull() instead of == null / != null is bad. We used those operators in Java for 20 years before Objects.isNull / Objects.nonNull methods appeared (together with introduction of lambdas in Java 8) and there is no reason to change that practice. Using isNull() / notNull() just introduces inconsistent style and confuse local static analysis tools. They are no more clear than a language feature existed since day one.

Read the JavaDoc - those methods have quite specific purpose and it is not to replace / compete with (in)equality operators:

API Note: This method exists to be used as a Predicate, filter(Objects::isNull)

Regarding the original question - there is currently no way to force static imports for particular methods in Checkstyle (and any other static analysis tool for Java I know of). Only forbidding is possible. I really wish it would be possible to do both as I myself find static imports quite useful and providing better clarity to the code in many circumstances (as well as a source of abuse such as in afore mentioned example and trying to import too ambiguous names such as of or ofNullable).

But currently you are limited to making your own Checkstyle plugin for that.