Is it possible to implement package hierarchy hierarchy in Java?

Basically, I have packages ...

com.me.application com.me.application.thing com.me.library 

I want to apply a rule that nothing in com.me.application can include com.me.library , except for things in com.me.application.thing .

Is this possible at the Java, Maven, classpath, or any other level of Java code that would be roughly equivalent to binding in C?

+1
source share
4 answers

The only way I can think of is through AspectJ .

AspectJ is an aspect-oriented language that is used to add cross-cutting issues to your application through a separate compilation process. One of AspectJ's classic uses is a political application that matches your scenario.

Basically, you declare rules that determine which package the code can be called from, and throw a compilation error whenever you encounter a method call (or in your case a variable declaration) that violates these rules. You can find out more in the excellent AspectJ book in action.

AspectJ can be easily integrated into Maven builds through the AspectJ plugin

And if you use AspectJ only to enforce the rules, you will not have any additional runtime dependencies, since your bytecode will not be changed.

+2
source

Instead of trying to get the compiler to do this, why not use source code analysis?

I would recommend using the architecture rules engine , which is now built into Sonar . Combine this with the build breaker plugin, and you can cause the build to fail if the developers break your hierarchy rules.

+3
source

You can force checks using the Checkstyle import control rule. Configure the Maven Checkstyle plugin in your pom.xml and any violations can be installed to cause the build to fail.

+2
source

You will need to create com.me.application, com.me.application.thing and com.me.library through separate maven projects, each of which creates a jar file. pom for com.me.application will not include a dependency on com.me.library and pom for com.me.application.thing will include a dependency on com.me.library.

But this is a strange package structure. Why do you want to prevent this?

0
source

Source: https://habr.com/ru/post/1488102/


All Articles