How to get the enclosing method node with JDT?

▼魔方 西西 提交于 2020-01-03 16:47:19

问题


When I have a method foo() that calls bar(), how can I get the foo() AST node from MethodInvocation node (or whatever statements/expressions in the method)? For example, I need to know the IMethod foo from b.bar().

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

回答1:


In JDT/UI we have a helper method to do this. Take a look at org.eclipse.jdt.internal.corext.dom.ASTNodes.getParent(ASTNode, int)




回答2:


I came up with this code, but I expect there are better ways to get the result.

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();
}



回答3:


The other trick might be letting the visitor store the caller information before visiting the MethodInvocation node:

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);

With AnotherClass Type:

public class AnotherClass {

    public int getValue()
    {
        return 10;
    }

    public int moved(int x, int y)
    {
        if (x > 30)
            return getValue();
        else
            return getValue();
    }
}

I could get the information:

TYPE(CLASS): AnotherClass
CALLER: getValue
CALLER: moved
INVOKE: getValue
INVOKE: getValue


来源:https://stackoverflow.com/questions/14449262/how-to-get-the-enclosing-method-node-with-jdt

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