Java Annotations Processor 来分析表达式? [英] Java Annotations Processor to analyze expressions?

查看:15
本文介绍了Java Annotations Processor 来分析表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Java 注释处理器,取得了很好的效果.现在我想做以下事情,据我所知这是不可能的.

I've been playing around with Java Annotation Processors, with great results. Now I would like to do the following, which as far as I can see is not possible.

我有几个实现构建器模式的类.比如说

I have several Classes that implement the Builder Pattern. Say for instance

new FooBuilder().doSomething("A").doSomethingElse("B").execute();

使用 execute() 方法终止方法调用的链"至关重要.否则,builder 基本上什么都不做.

It is vital that the "chain" of method calls is terminated using an execute() method. Otherwise, the builder will basically do nothing.

所以我想在编译时使用 JAP 来验证在某些表达式类型上是否存在 execute() 方法.不幸的是,我能检索到的最细粒度的信息似乎是在方法声明级别,而不是表达式.

So I wanted to use JAP to verify the presence of an execute() method on certain expression types at compile time. Unfortunately it appears that the finest-grained information I can retrieve is on method declaration level, not expressions.

我想要的一切可能吗?

推荐答案

Java 的标准注解处理器仅在声明处提供回调,例如方法和字段声明.

Java's standard annotation processors provide a callback only at declarations, such as method and field declarations.

可以使用注释处理器来分析表达式,但需要做更多的工作.您必须编写一个注解处理器,在每个方法中获取该方法的 AST(抽象语法树或解析树),然后访问该方法中的每个表达式.AST 是特定于编译器的.

It's possible to use an annotation processor to analyze expressions, but it's a bit more work. You will have to write an annotation processor that, at each method, obtains the AST (abstract syntax tree or parse tree) for the method and then visits each expression in the method. The AST is compiler-specific.

执行此操作的两个最著名的项目是 Checker Framework龙目岛项目.也许您可以从他们的实现中汲取灵感,甚至可以在其中之一之上编写您的注释处理器.

The two best-known projects that do this are the Checker Framework and Project Lombok. Maybe you could take inspiration from their implementations, or even write your annotation processor on top of one of them.

这篇关于Java Annotations Processor 来分析表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆