tags:

views:

581

answers:

7

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

+1  A: 

Could you use a custom doclet with JavaDoc?

Doclet.com may provide more information.

Rich
A: 

JavaCC is a "compiler-compiler" (parser generator) for Java. There are many grammar files for it, including one for Java 1.5.

unwind
+1  A: 

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.

Upul
+1  A: 

Both Eclipse and Netbeans have libraries for parsing the source code and creating Abstract Syntax Tree from it which would let you extract what you want.

willcodejavaforfood
+1  A: 

You can build your parser with one of parser generators:

  1. ANTLR
  2. JavaCC
  3. SableCC

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.

Rorick
+1  A: 

Java source reflection: http://ws.apache.org/jaxme/js/jparser.html

BTW, I haven't used it myself. I just googled for your question, because I also wanted to know the answer. The description in that link and javadoc looked promising. It is based on ANTLR.

Fakrudeen
+7  A: 

Download the java parser from http://code.google.com/p/javaparser/

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);
arcticfox
Great answer. Appreciate the effort. Thanks.
subtenante