Java注释处理器可以分析表达式

Java注释处理器可以分析表达式

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

问题描述

我一直在使用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.

我有几个实现Builder模式的类.比如说

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

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

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

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框架龙目岛项目.也许您可以从它们的实现中汲取灵感,甚至可以在其中之一的基础上编写注释处理器.

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注释处理器可以分析表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:31