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).
Going to a command line and typing java -version can tell us for sure if Java is installed.
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).
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.
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\ ".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With