3

in my program I dynamically get the name of the .java file. In this file I need to find all methods, foreach method also all parameters (also with their annotations).

I read through the discussions here and found this https://code.google.com/p/javaparser/ javaparser, that seems pretty easy to use, but the problem is, that it is just for 1.5.

Than you mentioned, that Java 1.6 has already got built-in parser (javax.lang.model). But I can not figure out, how it works. Do you know any good tutorial/example of it?

Do you know any other way to parse java source file?

2
  • As a side note, .class files are quite easy to read and contain all required information (except maybe parameter names, I don't remember that). Commented Jul 13, 2014 at 21:40
  • I know that .class files are easy to read (reflection), but I do not know, how to make .class file with that javax.lang.model and load it into some Class-variable. Commented Jul 14, 2014 at 5:34

2 Answers 2

3

How about using Doclet API?
Normally, This API is used from bat file, but you can invoke programmatically like the following.

IMPORTANT: This API exists in not rt.jar(JRE) but tools.jar (JDK). So you need to add tool.jar into classpath.

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doclet;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.javadoc.Main;

public class DocletTest {

    public static void main(String[] args) {
        Main.execute("", Analyzer.class.getName(), new String[] {"path/to/your/file.java"});
    }

    public static class Analyzer extends Doclet {

        public static boolean start(RootDoc root) {
            for (ClassDoc classDoc : root.classes()) {
                System.out.println("Class: " + classDoc.qualifiedName());

                for (MethodDoc methodDoc : classDoc.methods()) {
                    System.out.println("  " + methodDoc.returnType() + " " + methodDoc.name() + methodDoc.signature());
                }
            }
            return false;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Take another look at the javaparser project. It has been updated to support all modern Java versions.

The Doclet API is really hard to use and is badly documented. It will be either going away or be replaced with something better, hopefully even in Java 1.9.

1 Comment

I confirm that the JavaParser project is well alive on GitHub. There are several contributors improving it and ready to help users. Among other things it can parse all the Java 8 code but it can be run on the Jre 6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.