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);


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

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

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

No comments: