Editing/Modifying a .java file programmatically? (not the .class file)

Viewed 11663

So, here is a piece of code using CodeModel that generates java code:

    JCodeModel cm = new JCodeModel();
    JDefinedClass dc = cm._class("foo.Bar");
    JMethod m = dc.method(0, int.class, "foo"); 
    m.body()._return(JExpr.lit(5));
    File f = new File("C:/target/classes");
    f.mkdirs();
    cm.build(f);

This code generates a .java file:

package foo;
public class Bar {

       int foo() {
        return  5;
    }
}

However, I DO NOT want CodeModel to create a new java file for me. I do have a .java file already and would like to add a few lines of code to a method inside it. So, I would like the API to modify the java file directly/ create a modified copy of it. Is there a way to doing this?

4 Answers

You're really going to need a full parse of the code you want to modify to ensure you insert code into the correct location. I'd have thought your best bet would be to make use of an existing parse tool that allows code to be rewritten, rather than to try and do something by hand.

The Eclipse IDE does something like this to support code refactoring. This article might be helpful.

What you want is a program transformation system. This is a tool that parses your source file, and can apply transformations to modify it, an regenerates source code with the modifications.

A source-to-source transformation system accepts rules of the form of:

lhs -> rhs  if cond

where the lhs and rhs are souce patterns for valid fragments of the language and the cond checks that the rule is safe to apply. (Consider " ?x/?x -> 1 if ?x~=0"; you need the condition to verify that the division is valid).

One such tool is our DMS Software Reengineering Toolkit. DMS has full C, C++, C#, Java, COBOL, Python, PHP and ECMAScript front end parsers (as as many lesser known languages) and can apply such rules directly. DMS also provides symbol table construction and control and data flow analysis, as these are often useful in defining a cond for complex rules. If you want, you can also fall back to a "standard" procedural interface to visit tree nodes and modify ASTs.

Related