AST for current selected code in eclipse editor?

前端 未结 4 629
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 03:59

I need to get the AST for the current selection in the java editor fo eclipse. Basically I want to convert the selected java code in to some other form(maybe some other lang

4条回答
  •  萌比男神i
    2021-01-19 04:40

    Use the method org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.getActiveEditorJavaInput(). That returns the Java element edited in the current active editor. The return type is org.eclipse.jdt.core.IJavaElement, but if it's a Java file that's being edited, the run time type will be org.eclipse.jdt.core.ICompilationUnit.

    To get the AST, i.e., the org.eclipse.jdt.core.dom.CompilationUnit, you can use the following code:

    public static CompilationUnit getCompilationUnit(ICompilationUnit icu,
            IProgressMonitor monitor) {
        final ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(icu);
        parser.setResolveBindings(true);
        final CompilationUnit ret = (CompilationUnit) parser.createAST(monitor);
        return ret;
    }
    

    Keep in mind that this is for Java >= 5. For earlier versions you'll need to switch the argument to ASTParser.newParser().

    I realize that this question was answered but I wanted to shed light on the EditorUtility class, which is quite useful here.

提交回复
热议问题