javac.exe AST programmatic access example

前端 未结 2 1097
刺人心
刺人心 2020-12-13 01:26

Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?

2条回答
  •  孤街浪徒
    2020-12-13 01:58

    Compile and run this with -cp tools.jar (where you have to specify the location of your tools.jar, obviously).

    import com.sun.source.util.Trees;
    import javax.tools.JavaCompiler;
    import javax.tools.StandardJavaFileManager;
    import javax.tools.ToolProvider;
    
    public class JCTreeTest {
        private static final JavaCompiler javac
                = ToolProvider.getSystemJavaCompiler();
    
        public static void main(String[] args) {
            final StandardJavaFileManager jfm
                    = javac.getStandardFileManager(null, null, null);
            final JavaCompiler.CompilationTask task
                    = javac.getTask(null, jfm, null, null, null,
                      jfm.getJavaFileObjects(args));
            final Trees trees = Trees.instance(task);
            // Do stuff with "trees"
        }
    }
    

    It compiles and runs for me, though I have not played with the trees stuff myself, so you'll have to read the javadoc yourself. :-) Good luck!

提交回复
热议问题