我使用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 Symbol Solver的某个深处,它试图将File解析为一个值,当然会失败。
如何获取字段的标准名称?
答案 0 :(得分:0)
更新到3.8.0 后,将执行以下操作:
ResolvedType resolvedType = n.getScope().calculateResolvedType();
System.out.println(resolvedType.describe());