注释处理器,生成编译器错误

我正在尝试创建一个自定义注释,例如,确保字段或方法既是public也是final ,如果字段或方法不是publicfinal ,则会产生编译时错误,如下例所示:

 // Compiles @PublicFinal public final int var = 2; // Compiles @PublicFinal public final void myMethod {} // Compile time error @PublicFinal private final int fail = 2; 

到目前为止,我已经制作了两个自定义注释界面:

 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 { } 

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 annotations, RoundEnvironment roundEnv) { for (TypeElement typeElement : annotations) { Set 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; } } 

正如TODO所暗示的那样,我不知道如何生成编译时错误。 处理器的文档清楚地表明我不应该抛出exception,

如果处理器抛出未捕获的exception,该工具可能会停止其他活动注释处理器。

它继续描述引发错误条件时会发生什么,但现在如何引发错误条件。

问题:如何引发错误条件以使其生成编译时错误?

您可能需要processingEnv.getMessager().printMessage(Kind.ERROR, "method wasn't public and final", element)

Messager: “打印带有错误类型的消息会引发错误。”