【问题标题】:Is it possible to raise compile error on method's return type in annotation processing是否可以在注释处理中引发方法返回类型的编译错误
【发布时间】:2018-07-11 09:26:20
【问题描述】:

例如,如果您编写了具有错误返回值的覆盖方法。

new Runnable() {
  public int run() {

  }
};

编译器将标记您的返回值int 并给出错误“返回类型与 Runnable.run() 不兼容”。

现在我正在写一个注解处理器,我可以在返回值上标记错误吗?

Messager.printMessage(Kind.ERROR, "return value error", /* which element here? */)

编辑

编译错误不仅仅是因为注解处理。但是注释处理会引发编译错误。问题是如何在方法的返回类型上标记错误。答案可能是“有可能”或“不可能”。如果可能,请帮忙提供样品。

【问题讨论】:

  • 编译器错误与注解有何关系?
  • @LutzHorn 他们是不同的。但是它们是关联的,因为我们可以通过注释处理产生编译错误。问题是如何获取方法的返回类型元素。如果不可能,您可以回答“不可能”。

标签: java annotations annotation-processing annotation-processor


【解决方案1】:

这绝对是可能的。我会使用Tree API。

// In your annotation processor you get it's instance using
// processingEnv
Trees trees = Trees.instance(env);

现在,如果您必须使用 TreePathScanner 检查您的代码。所以例如获取您的元素的TreePath

TreePath path = trees.getPath(element);

现在用你的TreePathScanner遍历:

new ReturnTypeCheckingScanner().scan(path, null);

现在你的TreePathScanner 实现:

public class ReturnTypeCheckingScanner extends TreePathScanner<Void, Void> {

    @Override
    public Void visitMethod(MethodTree methodTree, Void aVoid) {
        Tree returnType = methodTree.getReturnType();
        if(invalidReturnType(returnType)) {
            trees.printMessage(
                ERROR,
                "Invalid return type",
                returnType,
                getCurrentPath().getCompilationUnit()
            );
        }
        return aVoid;
    }

}

直接使用MessagerElement API 应该也是可以的。但是你必须弄清楚,如何获取 ExecutableElement.getReturnType() 的元素(类型为TypeMirror)。

【讨论】:

  • 非常感谢。我稍后会尝试。据我了解,tool.jar 来自 javac API。如果我想它也可以在 eclipse 中工作,我还需要在 ECJ API 中实现它。我说的对吗?
猜你喜欢
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多