'How to prohibit usage of classes with certain annotation
In our organizations we've got several microservices and lots of libraries.
Some libraries define "public" classes that are not intended for public usage - only inside library in multiple packages (thus can't be package-private)
I'd like to add something similar to Kotlin's "internal" modifier - a checkstyle rule/annotation processor/test component that verifies that consumer applications don't import these classes.
for example, I will mark them as @ForInternalUsageOnly or put into package com.ourorg.mylib.internal_usage
what can be a non-copy-pasted (e.g. a jar or a gradle task) implementation that verifies that such classes are not imported? Preferably - on compilation level
Solution 1:[1]
It sounds like you should be using the Java 9+ module
feature, and its ability specify what classes are exposed outside of a given module.
Here are some references to get you started:
and there are lots of tutorials and videos.
While it should be possible to do what you propose using annotations and a checker, I can't recommend any practical examples.
Solution 2:[2]
You can achieve something like this with ArchUnit easily, your ArchRule would be something like -
@ArchTest
public static final ArchRule customArchRule = noClasses()
.should()
.dependOnClassesThat()
.areAnnotatedWith(ForInternalUsageOnly.class);
Assuming you are using it with JUnit 5 or 4, classes in noClasses()
are determined by @AnalyzeClasses
, you can read more about setting up and using ArchUnit from here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | VyomYdv |