[英]How to get the enclosing method node with JDT?
当我有一个调用bar()的方法foo()时,如何从MethodInvocation节点(或方法中的任何语句/表达式)获取foo()AST节点? 例如,我需要从b.bar()知道IMethod foo。
public void foo()
{
b.bar();
}
我提出了这个代码,但我希望有更好的方法来获得结果。
public static IMethod getMethodThatInvokesThisMethod(MethodInvocation node) {
ASTNode parentNode = node.getParent();
while (parentNode.getNodeType() != ASTNode.METHOD_DECLARATION) {
parentNode = parentNode.getParent();
}
MethodDeclaration md = (MethodDeclaration) parentNode;
IBinding binding = md.resolveBinding();
return (IMethod)binding.getJavaElement();
}
在JDT / UI中,我们有一个帮助方法来执行此操作。 看看org.eclipse.jdt.internal.corext.dom.ASTNodes.getParent(ASTNode, int)
另一个技巧可能是让访问者在访问MethodInvocation节点之前存储调用者信息:
ASTVisitor visitor = new ASTVisitor() {
public boolean visit(MethodDeclaration node) {
String caller = node.getName().toString();
System.out.println("CALLER: " + caller);
return true;
}
public boolean visit(MethodInvocation node) {
String methodName = node.getName().toString();
System.out.println("INVOKE: " + methodName);
使用AnotherClass类型:
public class AnotherClass {
public int getValue()
{
return 10;
}
public int moved(int x, int y)
{
if (x > 30)
return getValue();
else
return getValue();
}
}
我可以得到这些信息:
TYPE(CLASS): AnotherClass
CALLER: getValue
CALLER: moved
INVOKE: getValue
INVOKE: getValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.