Alex Rivera | Logout

How I can find all unused import programmatically?

Asked 2012-09-17T05:08:31.387
9

In my case there are two reason for doing that:

  • Sometimes people by mistake import classes which present in macbooks JDKs but absent in Linux. This causes build to fail on CI which are Linux based boxes. I doesn’t happen frequently, but when it does I'm thinking that there should be some smarter way to find out that earlier.
  • Unused imports trigger warning in IDE/code analysis. From time to time somebody need to spend time on cleaning that up. Even if its just single right click in IDE you still need to make PR, pass a build etc etc.

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.

Edit
Report

2 Answers

11

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).

answered 2012-09-17T05:29:03.990
0

Aren't these unrelated questions? If you import classes only present in the local JDK, these imports are used (just unsatisfied). For either problem, I recommend solving it in the IDE so the problem will be detected when code is written, rather than prior to checkin (the earlier the detection, the easier the fix ...).

In eclipse, you could prevent unsatisfied imports with access rules, and automatically fix imports whenever a source file is saved by enabling the appropriate save action. If you check these settings into version control, you can easily share them with the team.

answered 2012-09-17T06:25:29.983

Your Answer