注释处理器,生成编译器错误
问题内容:
我正在尝试创建一个自定义批注,例如,以确保字段或方法为public
and final
,并且如果该字段或方法不为public
and
final
,则将生成编译时错误,如以下示例所示:
// 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<? 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;
}
}
如所示TODO
,我不知道如何生成编译时错误。Processor
的文档清楚地表明,我不应该抛出异常,
如果处理器抛出未捕获的异常,则该工具可能会停止其他活动的注释处理器。
它继续描述了引发错误条件时会发生什么,但是现在描述了 如何 引发错误条件。
问题:如何引发错误条件,使其产生编译时错误?
问题答案:
你可能想要processingEnv.getMessager().printMessage(Kind.ERROR, "method wasn't public and final", element)
。
Messager:
“打印错误类型的消息会引发错误。”