Search code examples
javaeclipseeclipse-jdt

Getting field type in a method in eclipse


How do I programmatically get the field type from a statement inside a method like this :

Foo foo = getSomeFoo();

If it is field, I can know the type of the element.


Solution

  • You need to use Eclipse's AST

    ICompilationUnit icu = ...
    
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);
    parser.setSource(icu);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        @Override
        public boolean visit(VariableDeclarationStatement node) {
            System.out.println("node=" + node);
            System.out.println("node.getType()=" + node.getType());
            return true;
        }
    });