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);
        jp.parse(file);
        Iterator<JavaSource> javaSources = jsf.getJavaSources();
        JavaSource javaSource = javaSources.next();
        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
                        .getType().toString()));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            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.
    <dependencies>
        <dependency>
            <groupId>org.apache.ws.jaxme</groupId>
            <artifactId>jaxmejs</artifactId>
            <version>0.5.2</version>
        </dependency>
        <dependency>
         <groupId>antlr</groupId>
         <artifactId>antlr</artifactId>
         <version>2.7.7</version>
        </dependency>
    </dependencies>
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).