Java : parse java source code, extract methods
JavaParsingJava Problem Overview
I wish to parse java source code files, and extract the methods source code.
I would need a method like this :
/** Returns a map with key = method name ; value = method source code */
Map<String,String> getMethods(File javaFile);
Is there a simple way to achieve this, a library to help me build my method, etc. ?
Java Solutions
Solution 1 - Java
Download the java parser from <https://javaparser.org/>
You'll have to write some code. This code will invoke the parser... it will return you a CompilationUnit:
InputStream in = null;
CompilationUnit cu = null;
try
{
in = new SEDInputStream(filename);
cu = JavaParser.parse(in);
}
catch(ParseException x)
{
// handle parse exceptions here.
}
finally
{
in.close();
}
return cu;
Note: SEDInputStream is a subclass of input stream. You can use a FileInputStream if you want.
You'll have to create a visitor. Your visitor will be easy because you're only interested in methods:
public class MethodVisitor extends VoidVisitorAdapter
{
public void visit(MethodDeclaration n, Object arg)
{
// extract method information here.
// put in to hashmap
}
}
To invoke the visitor, do this:
MethodVisitor visitor = new MethodVisitor();
visitor.visit(cu, null);
Solution 2 - Java
QDOX is a more lightweight parser, that does only parse down to the method level, i.e. the method body is not being parsed into statements. It gives you more or less, what you ask for, even though the you would have navigate the model to find the right name, as it doesn't index classes and methods by name.
Solution 3 - Java
You can build your parser with one of parser generators:
Also, you can use (or study how it works) something ready-made. There are Java Tree Builder which uses JavaCC and RefactorIt which uses ANTLR.
Solution 4 - Java
Could you use a custom doclet with JavaDoc?
Doclet.com may provide more information.
Solution 5 - Java
JavaCC is a "compiler-compiler" (parser generator) for Java. There are many grammar files for it, including one for Java 1.5.
Solution 6 - Java
I think you can use ANTLR parser generator.
It is very easy to use and ANTLR site has a lot of examples written in Java.
Also it comes with a plug-in for eclipse.
Solution 7 - Java
You can use this repo. https://github.com/minqukanq/method-extractor/blob/main/README.md
method-extractor is a parser for Java, Python.