【问题标题】:Find Class name of Super Keyword in JavaParser在 JavaParser 中查找 Super 关键字的类名
【发布时间】:2020-09-02 06:46:10
【问题描述】:

我正在开发一个基于JavaParser 的Java 应用程序。我不知道如何获取方法体中使用的 Super 关键字 的类名。例如,我需要知道下面代码中的 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

【问题讨论】:

  • exprMethodCallExpr 类型吗?如果是这样,看来您必须使用 getScope(): expr.getScope().asSuperExpr()
  • 我实际上做了同样的事情,但没有工作。我更新了问题以显示这一点。
  • super 在您的示例中是指 B 类(这是当前 C 类的超类),而不是 A。
  • 假设C类直接继承自A类,没有任何作用,结果依然为null。

标签: java super javaparser


【解决方案1】:

我找到了正确的方法。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 2017-07-19
    • 1970-01-01
    • 2014-06-19
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多