英文:
Find Class name of Super Keyword in JavaParser
问题
我正在基于JavaParser开发一个Java应用程序。我不知道如何获取方法体中使用的Super关键字所指的类名。例如,我需要知道下面代码中的Super关键字是指类A。
class A {
public void bar(){...}
}
class B extends A {}
class C extends B {
void foo(){
super.bar() // 我想知道super关键字指的是类A。
}
}
我检查了JavaParser提供的这些函数(1、2和3),但它们都不起作用,都返回null。
MethodCallExpr methodCallExpr = ...
Optional<Expression> scope = methodCallExpr.getScope();
SuperExpr superExp = scope.get().asSuperExpr();
1. superExp.findAll(ClassOrInterfaceDeclaration.class); 和
2. superExp.getTypeName();
3. superExp.getClassExpr(); //我不知道为什么这个方法也返回null
英文:
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
答案1
得分: 3
我找到了正确的方法。
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);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论