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

kuporific:

我正在尝试创建一个自定义批注,例如,以确保字段或方法为publicand final,并且如果该字段或​​方法不为publicand 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: “打印错误类型的消息会引发错误。”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章