2
我試圖編碼rfc度量(響應類),它計數方法聲明+方法調用。計數方法聲明+方法使用JavaParser在類中調用
方法聲明工作正常,但我在使用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()*
事實上,該代碼檢查方法調用,但在我case我不希望它計數庫方法調用像System.out.println (toString())
,我想它的國家t只有toString()
。
如果您有更好的代碼或其他API使用...歡迎任何幫助,請提前致謝。
這是一個經典的例子,說明爲什麼在構建任何類型的靜態分析工具時,解析後的生活很重要。請參閱http://www.semdesigns.com/Products/DMS/LifeAfterParsing.html – 2016-11-13 19:08:54