问题
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