Search code examples
javareflectionassemblycode-generationjavassist

Javassist : How do I call a nondefault constructor on a dynamically generated class?


I have put a lot of time into this problem and to no avail. Ideally I would like to pass a parameter into the constructor of a dynamically generated class. The problem is that I don't know how to instantiate with a parameterized constructor.

My approach to instantiation so far has been ...

CtClass myClass . . . 
myClass.addInterfaces(.... //assume I have an interface that is nondynamic
InterfaceName interfaceinstance = (InterfaceName) (myClass.toClass().newInstance());

Is there a better way to go about this that will provide more flexibility?

Thank you so much!

RB


Solution

  • assume you want to invoke constructor, which takes a string as param (I suppose you know the signature)

    Class clazz = object.getClass();
    Constructor ctr = clazz.getDeclaredConstructor(String.class);
    Object instance = ctr.newInstance("Foo");