gpt4 book ai didi

java - 使用 JavaParser 计算类中的方法声明 + 方法调用

转载 作者:行者123 更新时间:2023-11-29 09:03:20 25 4
gpt4 key购买 nike

我正在尝试编写 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 可以使用...欢迎任何帮助,在此先感谢您。

最佳答案

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

您可以使用 JavaSymbolSolver 轻松做到这一点,这是一个为补充 JavaParser 而创建的库。在实践中你调用:

JavaParserFacade.solveMethodAsUsage(myMethodCallExpr)

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

关于java - 使用 JavaParser 计算类中的方法声明 + 方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16214783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com