Saturday, March 20, 2010

Parse Java Source Code with JaxMe JS

You can parse Java Source Code easily with JaxMe JS.

Here is a code examples that demonstrates how to use JaxME JS. The code won't work as it is, but it's useful to demonstrate JaxMe JS usage in practice.

A weakness of JaxMe JS is that it can only parse and generate Java 1.4 source code files. As of version 2, JaxMe JS cannot parse/generate Java 5 source code that uses Java generics and Java annotations features.

        JavaSourceFactory jsf = new JavaSourceFactory();
        JavaParser jp = new JavaParser(jsf);
        Iterator<JavaSource> javaSources = jsf.getJavaSources();
        JavaSource javaSource =;
        ObjectModel model = new ObjectModel(javaSource.getPackageName(), javaSource.getClassName());
        try {
            for (JavaField field : javaSource.getFields()) {
                log.log(Level.INFO, "Processing " + field.asString());
                model.addProperty(field.getName(), Class.forName(field
        } catch (ClassNotFoundException e) {
            throw new ParserException(e);
        return model; 
Put the following on your Maven project's pom.xml to specify the JaxME JS depency. ANTLR must be specified too.
For more information on grammar/language parsing and code generation with Java (and ANTLR), get the book The Definitive Antlr Reference: Building Domain-Specific Languages (Pragmatic Programmers).