JavaSymbolSolver:获取字段的完全限定名称
JavaSymbolSolver: get field's fully qualified name
我使用 JavaParser(来自 javaparser.org)和 javasymbolsolver 来解析 Java。
我有一个访问 File.separator
的简单 Java 源代码(请参阅源代码中的多行字符串);我希望我的程序打印 java.io.File.fileseparator
。相反,它打印 File.separator
并且我得到 UnsolvedSymbolException{context='File', name='Solving File'}
;然后它打印 System.out
我得到 UnsolvedSymbolException{context='System', name='Solving System'}
.
@Test
public void parserTest() {
CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
combinedTypeSolver.add(new ReflectionTypeSolver());
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(combinedTypeSolver);
JavaParser.getStaticConfiguration().setSymbolResolver(symbolSolver);
CompilationUnit compilationUnit = JavaParser.parse(
"import java.io.File;\n" +
"\n" +
"public class Main {\n" +
" static String s = File.separator;\n" +
" public static void main(String args[]) {\n" +
" System.out.println(s);\n" +
" }\n" +
"}\n");
compilationUnit.accept(
new ModifierVisitor<Void>() {
@Override
public Visitable visit(final FieldAccessExpr n, final Void arg) {
System.out.println(n);
try { // this does not work!!!
System.out.println(n.getScope().calculateResolvedType());
} catch (Exception e) {
e.printStackTrace();
}
return super.visit(n, arg);
}
},
null
);
}
据我所知,在 Java 符号求解器的某个深处,它试图将文件解析为一个值,当然失败了。
如何获取字段的完全限定名称?
更新到 3.8.0 后,以下工作:
ResolvedType resolvedType = n.getScope().calculateResolvedType();
System.out.println(resolvedType.describe());
我使用 JavaParser(来自 javaparser.org)和 javasymbolsolver 来解析 Java。
我有一个访问 File.separator
的简单 Java 源代码(请参阅源代码中的多行字符串);我希望我的程序打印 java.io.File.fileseparator
。相反,它打印 File.separator
并且我得到 UnsolvedSymbolException{context='File', name='Solving File'}
;然后它打印 System.out
我得到 UnsolvedSymbolException{context='System', name='Solving System'}
.
@Test
public void parserTest() {
CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
combinedTypeSolver.add(new ReflectionTypeSolver());
JavaSymbolSolver symbolSolver = new JavaSymbolSolver(combinedTypeSolver);
JavaParser.getStaticConfiguration().setSymbolResolver(symbolSolver);
CompilationUnit compilationUnit = JavaParser.parse(
"import java.io.File;\n" +
"\n" +
"public class Main {\n" +
" static String s = File.separator;\n" +
" public static void main(String args[]) {\n" +
" System.out.println(s);\n" +
" }\n" +
"}\n");
compilationUnit.accept(
new ModifierVisitor<Void>() {
@Override
public Visitable visit(final FieldAccessExpr n, final Void arg) {
System.out.println(n);
try { // this does not work!!!
System.out.println(n.getScope().calculateResolvedType());
} catch (Exception e) {
e.printStackTrace();
}
return super.visit(n, arg);
}
},
null
);
}
据我所知,在 Java 符号求解器的某个深处,它试图将文件解析为一个值,当然失败了。
如何获取字段的完全限定名称?
更新到 3.8.0 后,以下工作:
ResolvedType resolvedType = n.getScope().calculateResolvedType();
System.out.println(resolvedType.describe());