注释处理器,生成编译器错误 [英] Annotation Processor, generating a compiler error
问题描述
我正在尝试创建一个自定义注释,例如,确保字段或方法同时是 public
和 final
,并且会生成编译时错误如果字段或方法不是 public
和 final
,如以下示例所示:
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 { }
和处理器
:
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 的 文档 清楚地表明我不应该抛出异常,
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?
推荐答案
你可能想要 processingEnv.getMessager().printMessage(Kind.ERROR, "method was not public and final", element)
.
Messager: "打印错误消息kind 会引发错误."
Messager: "Printing a message with an error kind will raise an error."
这篇关于注释处理器,生成编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!