Java – Look for the class name of the super keyword in JavaParser

Look for the class name of the super keyword in JavaParser… here is a solution to the problem.

Look for the class name of the super keyword in JavaParser

I’m developing a Java application based on JavaParser. I don’t know how to get the class name of the Super keyword used in the method body. For example, I need to know that the Super keyword in the code below refers 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 returned 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

Solution

I found the right way.

ResolvedType resolvedType = superExp.calculateResolvedType();

If you also add JavaSymbolSolver to the parser configuration, this method works fine. JavaSymbolSolver is necessary to resolve references and find relationships 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);

Related Problems and Solutions