gpt4 book ai didi

java - 如何从 ExecutableElement 获取方法体

转载 作者:搜寻专家 更新时间:2023-10-31 20:09:29 24 4
gpt4 key购买 nike

在我的 AbstractProcessor 中,我能够从我创建的带有注释的类中获取所有方法:

List<? extends Element> allElements = processingEnv.getElementUtils().getAllMembers((TypeElement) bean);
List<ExecutableElement> methods = ElementFilter.methodsIn(allElements);

是否可以获取方法/ExecutableElement 的主体? API 似乎只处理签名和修饰符。

我可能会使用 this answer 的一些变体来访问专有 .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);

但是这些类带有警告:

This is NOT part of any supported API. If you write code that depends on this, you do so at your own risk. This code and its internal interfaces are subject to change or deletion without notice.

我希望可以从更通用的注释处理框架中访问注释方法的主体。

最佳答案

据我所知,注释框架不支持访问 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() 方法。

参见 this answer有关对引用的 JDK 工具类的依赖性的信息。

关于java - 如何从 ExecutableElement 获取方法体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com