【问题标题】:Annotation Processor, generating a compiler error注释处理器,生成编译器错误
【发布时间】:2013-07-31 00:33:56
【问题描述】:

我正在尝试创建一个自定义注释,例如,确保一个字段或方法既是public 又是final,如果字段或方法不是@987654324,则会生成编译时错误@ 和 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 的documentation 明确表示我不应该抛出异常,

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

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

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

【问题讨论】:

    标签: java annotations javac


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多