Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用JDT获取封闭方法节点?_Java_Eclipse_Eclipse Jdt - Fatal编程技术网

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

Java 如何使用JDT获取封闭方法节点?,java,eclipse,eclipse-jdt,Java,Eclipse,Eclipse Jdt,当我有一个调用bar()的方法foo()时,如何从MethodInvocation节点(或方法中的任何语句/表达式)获取foo()AST节点?例如,我需要从b.bar()了解IMethod foo 我提出了这个代码,但我希望有更好的方法来获得结果 public static IMethod getMethodThatInvokesThisMethod(MethodInvocation node) { ASTNode parentNode = node.getParent(); w

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


我提出了这个代码,但我希望有更好的方法来获得结果

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);
使用其他类别类型:

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

我认为这实际上是获取语句的封闭方法的标准方法。在我看来很好。这与我们在JDT/UI中使用的几乎相同。需要为此添加哪个依赖项?另外,这在3.5版中可用吗?您需要org.eclipse.jdt.ui插件。我还没有检查,但这种方法可能早于3.5.+1,它可以工作<代码>ASTNode parentNode=ASTNodes.getParent(methodInvocationNode,ASTNode.METHOD_声明)不幸的是,主要用例是检查在另一个类中调用的一个类的方法声明。这仅在调用方类也是声明类时才有用。
TYPE(CLASS): AnotherClass
CALLER: getValue
CALLER: moved
INVOKE: getValue
INVOKE: getValue