Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java parser for the Java language?

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.

like image 552
tangens Avatar asked Oct 31 '09 19:10

tangens


People also ask

What parser does Java use?

ANTLR. It is a popularly used context-free parser generator in Java. ANTLR can also generate parsers for other languages. ANTLR grammar contains two parts - the lexer and the parser rules.

How do you write parser in Java?

The first step in writing a parser is to tokenize the input string. This means to separate the input string into short bits that represent the basic entities in the expression. We could do this by hand, reading one character at a time and assembling the tokens character by character.

What is JavaCC used for?

JavaCC (Java Compiler Compiler) is an open-source parser generator and lexical analyzer generator written in the Java programming language. JavaCC is similar to yacc in that it generates a parser from a formal grammar written in EBNF notation.

Why is parse method used in Java?

SimpleDateFormat parse() Method in Java with Examples The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.


2 Answers

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).

like image 107
Ramon Avatar answered Oct 11 '22 11:10

Ramon


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);

like image 24
peter.murray.rust Avatar answered Oct 11 '22 11:10

peter.murray.rust