开发者

Can I redefine a method / constructor using reflection in Java?

I have a class called A and I need to create a new object of that class without calling its constructor. I want t开发者_开发问答o set all its attributes through reflection.

Can I redefine the constructor of class A using reflection?

Or is there any way other way to do this?


In the Sun/Oracle JVm you can use Unsafe.allocateInstance(Class). Otherwise you have to generate byte code to create the instance without calling a constructor. You could use ASM for this. You cannot create an instance without a constructor using Reflection alone.

BTW: You can define a new method using byte code manipulation, but to add a constructor, you have to change the class before it is loaded. (This is tricky to do)


Invoke the object with the constructor that takes the least amount of arguments; using dummy arguments. Then proceed to manipulate the object however you like.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜