I am developing a Java application based on JavaParser. I do not know how to get class name of Super keyword used in a method body. As an example, I need to know Super keyword in the below code is referred to class 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.
}
}
I checked these functions (1, 2, and 3) provided by JavaParser, but none of them worked, all return 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
I find the right method.
ResolvedType resolvedType = superExp.calculateResolvedType();
This method works correctly if you also add the JavaSymbolSolver to the parser configuration. JavaSymbolSolver is necessary to resolve references and find relations between nodes.
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);