Code Generation

You can easily write code that writes code.

Here's a bit of TestGenerator.java.

public class TestGenerator {
    private String generateCode(Class cl) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter code = new PrintWriter(stringWriter);

        generateBoilerplate(code);
        generateClassCode(code, cl);
        // ... and so on
        return stringWriter.toString();
    }
/**
 * File: $RCSfile: generation.html,v $
 * Version: $Revision: 1.1 $, $Date: 2006/03/29 22:04:05 $
 *
 * Copyright 2006 Activant Solutions Inc.
 * All rights reserved
 */

    private void generateBoilerplate(PrintWriter code) {
        code.println("/**");
        code.println(" * File: $RCSfile: $");
        code.println(" * Version: $Revision: $, $Date: $");
        code.println(" *");
        code.println(" * Copyright 2006 Activant Solutions Inc.");
        code.println(" */");
        code.println();
    }
    private void generateClassCode(PrintWriter code, Class cl) {
        String className   = stripPackage(cl.getName()) + "Test";
        String packageName = cl.getPackage().getName();

        code.println("package " + packageName + ";");
        code.println();
        code.println("import junit.framework.*;");
        code.println();
        code.println("public class " + className 
                                     + " extends TestCase {");
        code.println();
        code.println("    public " + className + "(String name) {");
        code.println("        super(name);");
        code.println("    }");
        code.println();
    }    
}