有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用JDT获取封闭方法节点?

当我有一个调用bar()的方法foo()时,如何从MethodInvocation节点(或方法中的任何语句/表达式)获取foo()AST节点?例如,我需要知道b.bar()中的IMethod foo

public void foo()
{
    b.bar();
}

共 (2) 个答案

  1. # 1 楼答案

    另一个技巧可能是让访问者在访问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);
    

    另一类类型:

    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
    
  2. # 2 楼答案

    在JDT/UI中,我们有一个助手方法来实现这一点。看看org.eclipse.jdt.internal.corext.dom.ASTNodes.getParent(ASTNode, int)