Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java source code parsers/generators [closed]

Tags:

I need tools to:

  • Conveniently parse Java source code and easily access given elements.

  • Easily generate source code files, to easily transform data structures into code

Any good tips, libraries, frameworks, tools? Thank you for help.

like image 499
Jarek Avatar asked Aug 09 '11 16:08

Jarek


People also ask

How does a parser generator work?

A parser generator takes a grammar as input and automatically generates source code that can parse streams of characters using the grammar. The generated code is a parser, which takes a sequence of characters and tries to match the sequence against the grammar.

Which tool is used to generate the parser program?

YACC provides a tool to produce a parser for a given grammar. YACC is a program designed to compile a LALR (1) grammar.

What is generated as an output from the parser?

The output from the parser is assumed to be a representation of the parse tree (example shown above) for the stream of tokens produced by the scanner.

How is parsing done in Java?

There are many Java classes that have the parse() method. Usually the parse() method receives some string as input, "extracts" the necessary information from it and converts it into an object of the calling class. For example, it received a string and returned the date that was "hiding" in this string.


2 Answers

If you need to parse existing source code, use JavaParser. It gives you visitor-based access to the AST. You can write new code, but many things are a pain (e.g. referencing other classes)

If you need to generate source code use CodeModel. It lets you programmatically create classes, packages, methods etc, and it's very easy to use. However, I don't think it can import existing code.

Both are pretty awesome in their respective domains.

like image 75
Sean Patrick Floyd Avatar answered Sep 20 '22 18:09

Sean Patrick Floyd


Since Java 6, the compiler has an API included in the JDK. Through it you can access the results of the Java parser through the javax.lang.model APIs. The same functionality was present with JDK5 in the form of the Mirror API. There's a good introductory article here.

The best code generation tool I've seen is CodeModel. It has a very simple API and can generate multiple Java source files at once.

like image 21
Daniel Avatar answered Sep 18 '22 18:09

Daniel