Skip to content

Instantly share code, notes, and snippets.

@johncarl81
Created November 25, 2013 19:23
Show Gist options
  • Save johncarl81/7647146 to your computer and use it in GitHub Desktop.
Save johncarl81/7647146 to your computer and use it in GitHub Desktop.
public class CodeModelIfForExample {
private static final String CLASS_NAME = "TestClass";
public static void main(String args[]) throws Exception{
JCodeModel codeModel = new JCodeModel();
JDefinedClass c = codeModel._class(CLASS_NAME);
writeIfElse(codeModel, c);
writeForLoop(codeModel, c);
StringCodeWriter codeWriter = new StringCodeWriter();
codeModel.build(codeWriter);
System.out.println(codeWriter.getOutput().get(CLASS_NAME + ".java"));
}
public static void writeIfElse(JCodeModel codeModel, JDefinedClass c){
JMethod method = c.method(JMod.PUBLIC, codeModel.VOID, "testIf");
JVar input = method.param(codeModel.INT, "input");
JBlock body = method.body();
JConditional condition = body._if(input.lt(JExpr.lit(42)));
condition._then().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(JExpr.lit("hello")));
condition._else().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(JExpr.lit("world")));
}
public static void writeForLoop(JCodeModel codeModel, JDefinedClass c){
JMethod method = c.method(JMod.PUBLIC, codeModel.VOID, "testFor");
JVar input = method.param(int.class, "input");
JBlock body = method.body();
JForLoop forLoop = body._for();
JVar ivar = forLoop.init(codeModel.INT, "i", JExpr.lit(0));
forLoop.test(ivar.lt(JExpr.lit(42)));
forLoop.update(ivar.assignPlus(JExpr.lit(1)));
forLoop.body().add(
codeModel.ref(System.class).staticRef("out").invoke("println").arg(ivar));
}
public static class StringCodeWriter extends CodeWriter {
private Map<String, ByteArrayOutputStream> streams = new HashMap<String, ByteArrayOutputStream>();
@Override
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
String packageFileName = pkg.name() + fileName;
if (!streams.containsKey(packageFileName)) {
streams.put(packageFileName, new ByteArrayOutputStream());
}
return streams.get(packageFileName);
}
@Override
public void close() throws IOException {
for (OutputStream outputStream : streams.values()) {
outputStream.flush();
outputStream.close();
}
}
public String getValue(String packageFileName) {
return new String(streams.get(packageFileName).toByteArray());
}
public Map<String, String> getOutput() {
Map<String, String> outputMap = new HashMap<String, String>();
for (Map.Entry<String, ByteArrayOutputStream> byteStreamEntry : streams.entrySet()) {
outputMap.put(byteStreamEntry.getKey(),
new String(byteStreamEntry.getValue().toByteArray()));
}
return outputMap;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment