Let's say I have an internal method, which should be used only in certain situations.
Is there any possibility, in Eclipse, to mark it as internal and show a warning when used to prevent me or people who will use my API to use it by mistake not knowing what they're doing. I can't change its visibility as it might be used in other packages/non-extending classes too.
Something like this:
@Internal
public void doSomeInternalStuff()
{
// ...
}
And then, a warning in Eclipse:
You get the point.
Any hope?
JSR269 (Pluggable Annotation Processor API) allows you to write custom annotation processors that can handle custom annotations and enable you to print errors or warning using a javax.annotation.processing.Messager
.
Below is an example.
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
@SupportedAnnotationTypes("fully.qualified.name.of.InternalAnnotationType")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class CustomAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(InternalAnnotationType.class)) {
InternalAnnotationType internalAnnotation = element.getAnnotation(InternalAnnotationType.class);
String message = "The method " + element.getSimpleName()
+ " is marked internal and its use is discouraged";
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message);
}
return true;
}
}
In Eclipse, you can register annotation processors in your Java Compiler by right-clicking on your project, then selecting Properties -> Java Compiler -> Annotation Processing -> Factory Path and adding the Jar that contains your custom annotation processor. Here is an interesting post that explains the details.
Alternatively, you can put all of your "internal" method API inside a dedicated class, and add an access rule for that class in your Eclipse build path, so that any code in your project that depends on this class would display a warning.
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