How to prevent fully qualified names in Java code

2019-06-18 16:08发布

问题:

Is it possible to check with checkstyle if a java project is using fully qualified names in the code. We want to prevent code like

if (org.apache.commons.lang3.StringUtils.isBlank(name)) { 
 ....
 ....
} 

and want to enforce that packages are instead imported instead.

Are there are other tools that can help us accomplish it?

回答1:

As far as I know, Checkstyle cannot do this. However, there is a PMD rule called UnnecessaryFullyQualifiedName which may be worth a look. IntelliJ plugins for PMD exist, for example QAPlug PMD, which is free to download.

Be prepared to see a lot of false positives though. For example, two classes which share the same simple name cannot be referenced without a fully qualified class name (e.g. foo.A and bar.A). Might also be that PMD actually checks for this case, it may be worth a try.



回答2:

FTR I've just raised https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/462 about potentially adding this to Checkstyle some time .. contributions welcome! ;-)