Java Annotations Processor to analyze expressions?

喜夏-厌秋 提交于 2020-08-19 11:03:22

问题


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();

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

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.

Is what I want at all possible?


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/38224469/java-annotations-processor-to-analyze-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!