How to check for package references in a Java source

In the java source I do not want to use any kind of package. For example, I do not want to refer to swing, or io, or to another.

Is there a system for checking that at compile time or during testing?

For example, with alleged annotation

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

Why do I need it?

Because I have an application with a swing, and I want to reorganize it with the part that uses swing, and the other, which is not there, because I want to port it to other ui files (web, pda, etc.).

Thanks.

+7
source share
6 answers

I do not know such a tool, but creating it is not so difficult. References to all used classes are encoded in the class file. Using some classfile library , you can check cool files, and all the classes (or packages) used are listed. If annotations like @NoPaquage are inserted, then the tool can simply check if the class really uses these packages.

+3
source

I can come up with one pretty hacky way to do this. However, you need to have a list of such forbidden classes, not just packages. Let's say you want to ban the use of javax.swing.JFrame .

Just create below fake class.

 package javax.swing; class JFrame { } 

Please note that the class is not publicly available, so any attempt to import it leads to a compilation error " The type javax.swing.JFrame is not visible. "

You can create a JAR file from all such forbidden classes and make sure that the class loader is loaded last . This guarantees a specific compiler error. You can simply include / exclude this JAR file whenever you want to run this test - a trivial task when using ant.

+2
source

I think it would be very difficult, since it is possible to use the class using reflection to get what it wants.

If I tried to do this, I would write my own custom class loader, but I'm not sure if the class loader interface is aware which class is actually trying to load. I think you can use a custom class loader if you want to prohibit the use of all code with specific code, but if you want it to be more specific to the class, you might need something manual, like grep-ing for code?

0
source

Something like that:

 $ find srcTree -name \*.java | xargs grep javax\\.swing 
0
source

You cannot have the JVM filter that you write. However, you can use generics to restrict the classes allowed in all public APIs. You can also limit inheritance as follows:

 class Parent { public Parent() throws Exception { if (this instanceof Child) throw new Exception("It a child"); } } public class Child extends Parent { public Child() throws Exception { super(); } } 
0
source

You can select the package that you want to use in the import area.

In Eclipse, you can choose the package from which your class came from.

You need to remove the import line to select a class in another package.

0
source

All Articles