在我的AbstractProcessor中,我能够从一个带有一些注释的类中获取所有方法,我创建了:
List extends Element> allElements = processingEnv.getElementUtils().getAllMembers((TypeElement) bean);
List methods = ElementFilter.methodsIn(allElements);
有可能获取方法/ ExecutableElement的主体吗? API似乎只处理签名和修饰符.
我可能会使用这个答案的一些变体:https://stackoverflow.com/a/34568708/6095334,来访问专有* .sun.**包中的类,例如com.sun.tools.javac.tree.JCTree $MethodTree:
MethodTree methodTree = trees.getTree(executableElement);
其中trees是在AbstractProcessor的init()方法中设置的com.sun.source.util.Trees的实例,如下所示:trees = Trees.instance(processingEnv);
但是这些类带有警告:这不是任何受支持的API的一部分.如果您编写的代码依赖于此,您需要自担风险.此代码及其内部接口可能会更改或删除,恕不另行通知.
我希望可以从更通用的注释处理框架中访问带注释的方法的主体.
解决方法:
据我所知,注释框架不支持访问ExecutableElement的主体.调用getEnclosedElements()会很诱人,但是正如javadoc所说:
Returns the elements that are, loosely speaking, directly enclosed by this element. A class or interface is considered to enclose the fields, methods, constructors, and member types that it directly declares. A package encloses the top-level classes and interfaces within it, but is not considered to enclose subpackages. Other kinds of elements are not currently considered to enclose any elements; however, that may change as this API or the programming language evolves.
对于我的项目,我设法从方法体中提取我需要的信息,如下所示:
MethodTree methodTree = trees.getTree(executableElement);
BlockTree blockTree = methodTree.getBody();
for (StatementTree statementTree : blockTree.getStatements()) {
// *do something with the statements*
}
其中com.sun.source.util.Trees trees = Trees.instance(processingEnv);是我在AbstractProcessor的init()方法中设置的实例字段.
标签:java,methods,annotation-processing
来源: https://codeday.me/bug/20190628/1310523.html