有 Java 编程相关的问题?

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

java ASTParser MethodInvocation如何检测静态方法调用

示例代码:

String.valueOf("test");

此代码的访问者:

cu.accept(new ASTVisitor()
{
    public boolean visit(MethodInvocation inv)
    {               
        System.out.println(inv);
        System.out.println(inv.getExpression().getClass());
        return true;
    }
});

输出:

String.valueOf("test")
class org.eclipse.jdt.core.dom.SimpleName

但非静态调用也将返回SimpleName

其次,我尝试获取resolveMethodBinding(),但这里没有方法可以帮助我检测是静态方法还是否

有人知道怎么做吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

    要像这样区分静态调用(而不是静态方法):

    myInteger.toString(); // Non-static call
    Integer.toString(myInteger); // Static call
    myInteger.toString(myInteger); // Non-static call (called from an object)
    

    您需要使用可用的绑定构建AST,并编写以下代码:

    cu.accept(new ASTVisitor()
    {
        public boolean visit(MethodInvocation inv)
        {               
            if (inv.getExpression() instanceof Name
                            && ((Name) inv.getExpression()).resolveBinding().getKind() == IBinding.TYPE)
            {
                // Static call
            }
            else
            {
                // Non-static call
            }
            return true;
        }
    });
    
  2. # 2 楼答案

    您需要使用可用的绑定构建AST,然后调用:

    IMethodBinding binding = inv.resolveMethodBinding();
    if (binding.getModifiers() & Modifier.STATIC > 0) {
      // method is static method
    } else {
      // method is not static
    }