Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

In a Java source, I don't want use some package. For instance, I don't want any reference to swing, or io, or other.

Is there a system to check that, at compile time, or at test time?

For instance, with supposed annotation

@NoPackage("javax.swing")
class Foo
{
    private JFrame fram; // NOT OK.
}

Why I need this? Because I have an application with swing, and I want refactor it with a part which uses swing, and other which doesn't, because I want to port it to other ui stuff (web, pda, etc).

like image 458
Istao Avatar asked Apr 11 '12 14:04

Istao


People also ask

How do I know if Java package is installed?

Going to a command line and typing java -version can tell us for sure if Java is installed.

Which packages are automatically imported in Java?

For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java. lang package and (2) the current package (the package for the current file).

What is source package in Java?

Source packages contain your Java class, interface, enumeration, and annotation type files. That is, anything with a . java extension. This package contains your application logic.

Where can I find Java packages?

The classes belonging to the package java. awt are stored in directory " $BASE_DIR\java\awt\ " while the classes of package java. awt. event are stored in directory " $BASE_DIR\java\awt\event\ ".


2 Answers

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.

like image 52
Alexei Kaigorodov Avatar answered Sep 29 '22 14:09

Alexei Kaigorodov


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.

like image 23
adarshr Avatar answered Sep 29 '22 14:09

adarshr