I'm using Javassist to generate a class and method at runtime but I want the generated code to have a reference to an existing object. For example:
public <T extends Event> Class<?> createClass(Class<T> eventClass, Consumer<T> consumer) throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass generatedClass = pool.makeClass("ClassName");
CtMethod ctMethod = new CtMethod(CtClass.voidType, "MethodName", new CtClass[] { pool.get(eventClass.getName()) }, generatedClass);
ctMethod.insertAfter("consumer.accept($1)"); //TODO: consumer being the consumer passed to the generateClass method
return (Class<?>) generatedClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()).newInstance();
}
consumer
is an object passed to the createClass() function but I want to use it in the generated method. What's the best way to do this?