开发者

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

开发者 https://www.devze.com 2023-03-15 20:23 出处:网络
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 insta

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 bee开发者_高级运维n ...

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号