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.
source share