Is there a Java parser for the Java language?

爷,独闯天下 提交于 2019-12-04 21:13:43

问题


I'm looking for a java library that allows me to parse a java source file and that gives me an AST representation of the code.

Actually I'm only interested in the class and method definitions with their annotations. I don't need the AST of the method code.

I'm using this information for code generation. This is why I can't compile the source file first to get the information from the resulting class file. The code wouldn't compile without errors until I generate some additional classes.


回答1:


Java 6 supports this as a native part of the compiler and has standard APIs for it (javax.lang.model). You can read up on it here. It is designed specifically for your use-case (i.e. code generation from annotations and source).




回答2:


ANTLR (http://www.antlr.org/) has a parser for the Java language and it also suports ASTs.

try

options {
    output=AST;
}

in the *.g file (I haven't tried it personally);




回答3:


You can try JavaCC with a grammar file for java language.




回答4:


I think NetBeans Javaparser might be something you'll be interested in.




回答5:


I found the project javaparser, which parses a single java file and returns a well formed AST.




回答6:


@tangens wrote about JavaParser but referenced a now outdated project.

There has been a fork in 2011 that is still actively maintained and now also parses Java 1.7 and 1.8.

You can find it there: https://github.com/javaparser/javaparser

Disclaimer: I am a contributor to that project.



来源:https://stackoverflow.com/questions/1655412/is-there-a-java-parser-for-the-java-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!