How to get method body from ExecutableElement

家住魔仙堡 提交于 2019-12-03 15:29:24
Hervian

To my knowledge, the annotation framework does not support accessing an ExecutableElement´s body. It would be tempting to call getEnclosedElements(), but as the javadoc states:

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.

For my project, I managed to extract the information I needed from the method body as follows:

MethodTree methodTree = trees.getTree(executableElement);
BlockTree blockTree = methodTree.getBody();
for (StatementTree statementTree : blockTree.getStatements()) {
  // *do something with the statements*
}

where com.sun.source.util.Trees trees = Trees.instance(processingEnv); is an instance field I set in the AbstractProcessor's init() method.

See this answer, for information about the dependency to the referenced jdk tool classes: https://stackoverflow.com/a/29585979/6095334

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