0

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?

kmecpp
  • 2,371
  • 1
  • 23
  • 38
  • 2
    You could add a field and a constructor receiving the consumer and storing it in the field. Basically, the same as the [`LambdaMetafactory`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/invoke/LambdaMetafactory.html) does. Alternatively, you could add a static field and assign it via Reflection after the class has been generated, but before creating instances. – Holger Mar 14 '21 at 13:43
  • Thanks. I originally used the static field method but generating a constructor/field worked a lot nicer. – kmecpp Mar 17 '21 at 19:34

0 Answers0