javareverse-engineeringstatic-analysis

How I can find all unused import programmatically?


In my case there are two reason for doing that:

I'm curious if there is any way to find unused imports programmatically (lets say from unit test) and fail locally if there are any.

Maybe failing a build because of unused import sounds harsh, but if it saves time for team overall it makes sens to do so (would love to hear opinion on that as well).

UPDATE:

I followed yegor256 suggestion and incorporated Checkstyle task with initially small subset of Sun Code Conventions (unused imports is one of them) and made it break a build if violations found.

After one week of trial we've got zero unused imports in our codebase and surprisingly zero complaints about this rule (by the way, Checkstyle is really fast: analyzing ~100KLoc taking less than one second).

As for using IDE for such analysis: yes, it good choice, but having this kind of checks run as part of automated build is better.


Solution

  • What you're trying to do is called static code analysis. Checkstyle can help you. If you're using Maven, this plugin will do the automation for you: http://maven.apache.org/plugins/maven-checkstyle-plugin/

    You can also take a look at qulice.com (I'm one of its developers), which integrates a few static analysis tools and pre-configures them (incl. Checkstyle, PMD, FindBugs).