我正在尝试编写 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);
}
}
测试.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())
,我希望它只计算toString()
。
如果您有更好的代码或其他 API 可以使用...欢迎任何帮助,在此先感谢您。