Search code examples
javajavaparserjavasymbolsolver

JavaSymbolSolver: get field's fully qualified name


I use JavaParser (from javaparser.org) and javasymbolsolver to parse Java.

I have a simple Java source that accesses File.separator (see the multi-line string in the source); I want my program to print java.io.File.fileseparator. Instead, it prints File.separator and I get UnsolvedSymbolException{context='File', name='Solving File'}; then it prints System.out and I get 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
    );
}

As I understand, somewhere deep in the Java Symbol Solver it tries to resolve File as a value, and of course fails.

How do I get the fully qualified name of a field?


Solution

  • After updating to 3.8.0, the following works:

    ResolvedType resolvedType = n.getScope().calculateResolvedType();
    System.out.println(resolvedType.describe());