计数方法声明+方法使用JavaParser在类中调用

时间:2013-04-25 12:27:35

标签: java parsing methods javaparser

我试图编写rfc指标(一个类的响应),它计算方法声明+方法调用。

方法声明工作正常,但我在使用JavaParser API计算方法调用时遇到了问题。

这是我的代码:

public class MethodPrinter {

    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("D://test.java");
        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        // visit and print the methods names
        MethodVisitor MV =new MethodVisitor();

        cu.accept(new VoidVisitorAdapter<Void>(){
            @Override
            public void visit(final MethodCallExpr n, final Void arg){
                System.out.println("method call :"+n);
                super.visit(n, arg);

            }
        }, null);
    }
}

test.java

package test;
import java.util.*;

public class ClassA 
{
  private int test;
  private ClassB classB = new ClassB();
  public void doSomething(int t){

    System.out.println ( toString());
    int i= doSomethingBasedOnClassBBV(classB.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

public class ClassB 
{
  private ClassA classA = new ClassA();
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }

  private String toString(){
    return "classB";
  }
  private String toString(){
    return "classB";
  }
  public void doSomethingBasedOneClassA(){
    System.out.println (classA.toString());
  }
  protected void doSomethingBasedOnClassB(){
    System.out.println (classB.toString());
  }
}

该代码的结果:

*method call :System.out.println(toString())

method call :toString()

method call :doSomethingBasedOnClassBBV(classB.toString())

method call :classB.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classA.toString())

method call :classA.toString()

method call :System.out.println(classB.toString())

method call :classB.toString()*

确实,该代码检查方法调用,但在我的情况下,我不希望它计算像System.out.println (toString())这样的库方法调用,我希望它只计算{{1} }。

如果您有更好的代码或其他API使用...欢迎任何帮助,请提前感谢。

1 个答案:

答案 0 :(得分:0)

您无法使用专门的解析器轻松解决问题,因为您需要解析方法调用并查明它是否是对标准库的方法部分的调用。

您可以使用JavaSymbolSolver轻松完成此操作,proof for ntddk.h是为补充JavaParser而创建的库。在实践中,你打电话:

JavaParserFacade.solveMethodAsUsage(myMethodCallExpr)

然后您返回一个MethodDeclaration,它会告诉您该方法的定义类型。获得该类型后,您可以查看该包,并检查它是否以javajavax开头,并将其排除。

相关问题