Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Eclipse warning on an annotation

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:

enter image description here

You get the point.

Any hope?

like image 777
wassup Avatar asked Jul 27 '14 10:07

wassup


1 Answers

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.

like image 171
M A Avatar answered Oct 12 '22 22:10

M A