Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javac configuration parameter for unused include warnings?

Is there a Sun command line parameter to provide warnings (or errors) in reference to unused import statements? The embedded eclipse javac compiler provides such warnings, but if the Sun / Oracle compiler has it as one of their -Xlint:XXX arguments, it is not well documented.

I'm looking to clean up an existing Java code base, which builds from the command line using Ant, and I would like integrate tracking and reporting of such statements into the nightly builds.

Some have suggested that imports have no effect on the compilation process, however looking at the compiler operations (with the -verbose flag) indicates that the compiler loads the imported classes unconditionally, even if they are not used in the written output. So, removing unused imports seems to have more benefits than just code comprehension at a glance.

like image 879
Edwin Buck Avatar asked Apr 05 '11 20:04

Edwin Buck


2 Answers

I recommend that you look at FindBugs instead for reporting on the cleanliness of the code as part of your nightly builds. FindBugs can detect a lot more potential problems than either the JDK Java compiler or the one in Eclipse.

like image 73
Konstantin Komissarchik Avatar answered Oct 12 '22 22:10

Konstantin Komissarchik


Use checkstyle, and configure the UnusedImports module to be used (or pick a default configuration that already uses it).

Checkstyle defines an unused import as:

  1. An non-wildcard import that is not referenced in the file.
  2. An import that is a duplicate of another import.
  3. An import from the java.lang package.
  4. An import from the same package as the class.
  5. (Optionally) an import that is only needed to resolve a JavaDoc link.

In practice, it creates a report that java.awt.Component is not used (along with the line number).

import java.awt.Component;
class FooBar {
    ...
}

It does have some limitations, in the sense it can be confused by members with the same name as an import; but, this failure rarely finds it's way into practice for most developers.

From the documentation as to the limitation

import java.awt.Component;
class FooBar {
    private Object Component; // IMHO bad practice
    ...
}

Would not flag Component as unused.

like image 31
Edwin Buck Avatar answered Oct 13 '22 00:10

Edwin Buck