How to check if there is no reference to a package in a Java source

I am not aware of such a tool, but it is not that complex to create one. References to all used classes are coded in classfile. Using some classfile library, classfiles can be inspected, and all used classes (or packages) listed. If annotations like @NoPaquage inserted, then the tool could just check if the class really dosent use that packages.


I can think of one rather hacky way to do this. However, you need to have a list of such forbidden classes, not just packages. Say, you want to forbid the usage of javax.swing.JFrame.

Just create the below fake class.

package javax.swing;

class JFrame {
}

Notice that the class isn't public, so any attempt to import it leads to the compilation error "The type javax.swing.JFrame is not visible."

You could create a JAR file out of all such forbidden classes and make sure they get loaded last by the classloader. This ensures that a compiler error definitely occurs. You can simply choose to include/exlude this JAR file whenever you want to run this test - a trivial task if using ant.

Tags:

Java