问题描述
我正在开发基于JavaParser的Java应用程序。我不知道如何获取方法正文中使用的超级关键字的类名。例如,我需要知道以下代码中的super关键字被引用为A类。
class A {
public void bar(){...}
}
class B extends A {}
class C extends B {
void foo(){
super.bar() // I want to find that the super keyword is referred to Class A.
}
}
我检查了JavaParser提供的这些功能(1、2和3),但是它们都没有起作用,都返回null。
MethodCallExpr methodCallExpr = ...
Optional<Expression> scope = methodCallExpr.getScope();
SuperExpr superExp = scope.get().asSuperExpr();
1. superExp.findAll(ClassOrInterfaceDeclaration.class); and
2. superExp.getTypeName();
3. superExp.getClassExpr(); //I do not kNow why this method also returns null
解决方法
我找到了正确的方法。
ResolvedType resolvedType = superExp.calculateResolvedType();
如果您还将JavaSymbolSolver也添加到解析器配置中,则此方法将正常工作。 JavaSymbolSolver是解析引用和查找节点之间关系的必要条件。
TypeSolver reflectionTypeSolver = new ReflectionTypeSolver();
TypeSolver javaParserTypeSolver = new JavaParserTypeSolver(projectSourceDir);
CombinedTypeSolver combinedSolver = new CombinedTypeSolver();
combinedSolver.add(reflectionTypeSolver);
combinedSolver.add(javaParserTypeSolver);
ParserConfiguration parserConfiguration = new ParserConfiguration()
.setSymbolResolver(new JavaSymbolSolver(combinedSolver));
SourceRoot sourceRoot = new SourceRoot(projectSourceDir.toPath());
sourceRoot.setParserConfiguration(parserConfiguration);