Parsing .java file to extract all features

Viewed 112

I need to parse .java file to do static analyze and extract information from the file like:

  1. variables
  2. methods
  3. annotations
  4. inner classes
  5. ...

I need to parse It at runtime something like this:

JavaClass c = parse("file.java");
c.getMethods();

I am not sure if there is any tool already exists, and if not can you please provide with some advice how to build it.

3 Answers

You definitely need to use a good parser for that.

ANTLR is a parser generator that comes with a huge library of ready to use grammars, one of which is Java. With that one it is easy to transform a java source file into an abstract syntax tree. On that tree do whatever analysis or transformation you need.

Have a look to the JavaDoc API. It provides everything you need, and you do not even need to write a parser of your own.

Ok, in the beginning it is far from being intuitive, but the good thing is, it works along the same line as an AnnotationProcessor, so you learn two things in one go.

Is your task an academic one? If not then I would consider supporting/joining an existing static analysis tool project like spotbugs, PMD, ...

And does it really need to be .java files or can it also be .class files? Most available static analysis tools for java work on bytecode. So why reinvent the wheel? Spotbugs for instance is using BCEL and ASM.

Related