Monday, February 16, 2009

Generating Bytecode


I've been looking at the Javassist project. It's really nice. It's a higher level API for manipulating and generating bytecode. Below is an example generating a new class that implements and interface, and then implements the interface. By generating this, it avoids reflection and is significantly faster in tests I've run.



ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass(classFunctionName);

cc.addInterface(pool.get("org.springmodules.validation.valang.functions.Function"));

StringBuilder generatedMethod = new StringBuilder();
generatedMethod.append("public Object getResult(Object target) {");
generatedMethod.append(" return ");
generatedMethod.append(" ((" + className + ")target).");
generatedMethod.append(property);
generatedMethod.append("();");

CtMethod m = CtNewMethod.make(generatedMethod.toString(), cc);
cc.addMethod(m);

result = (Function)cc.toClass().newInstance();

No comments: