Annotation Processor, generating a compiler error

孤者浪人 提交于 2019-11-30 12:01:29

问题


I'm trying to create a custom annotation that, for example, ensures that a field or method is both public and final, and would generate a compile time error if the field or method is not both public and final, as in these examples:

// Compiles
@PublicFinal
public final int var = 2;

// Compiles
@PublicFinal
public final void myMethod {}

// Compile time error
@PublicFinal
private final int fail = 2;

So far, I've made both the custom annotation interface:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface PublicFinal { }

and Processor:

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.util.Set;

@SupportedAnnotationTypes("PublicFinal")
public class PubicFinalProcessor extends AbstractProcessor
{
    @Override
    public boolean process(
            Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv)
    {
        for (TypeElement typeElement : annotations)
        {
            Set<Modifier> modifiers = typeElement.getModifiers();

            if (!modifiers.contains(Modifier.FINAL)
                    || !modifiers.contains(Modifier.PUBLIC))
            {
                // Compile time error.
                // TODO How do I raise an error?
            }
        }

        // All PublicFinal annotations are handled by this Processor.
        return true;
    }
}

As hinted by the TODO, I do not know how to generate the compile time error. The documentation of Processor makes it clear that I should not be throwing an exception,

If a processor throws an uncaught exception, the tool may cease other active annotation processors.

It goes on to describe what happens when an error condition is raised, but now how to raise an error condition.

Question: how do I raise an error condition such that it generates a compile time error?


回答1:


You probably want processingEnv.getMessager().printMessage(Kind.ERROR, "method wasn't public and final", element).

Messager: "Printing a message with an error kind will raise an error."



来源:https://stackoverflow.com/questions/17959728/annotation-processor-generating-a-compiler-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!