2

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?

Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • Have your tried to use fully qualified names in the to be parsed code? That is instead of `File.separator` use `java.io.File.separator`. And instead of simply `System.out` use `java.lang.System.out`. Looks like javaparser is not using the imports as expected?! – dpr Nov 29 '18 at 13:10
  • @dpr `UnsolvedSymbolException{context='unknown', name='io'}`, `UnsolvedSymbolException{context='java', name='Solving java'}`. It tries to resolve it as a value. – 18446744073709551615 Nov 29 '18 at 13:26

1 Answers1

4

After updating to 3.8.0, the following works:

ResolvedType resolvedType = n.getScope().calculateResolvedType();
System.out.println(resolvedType.describe());
18446744073709551615
  • 16,368
  • 4
  • 94
  • 127