How can I override methods in Java when I create an Object via reflection?

匆匆过客 提交于 2019-12-02 19:28:59
mhaller

No, it's not possible in the way of your example.

In your example, the Java compiler will create two separate classes:

MyObject.class
MyObject$1.class

The latter being the one with the overridden method. In this case, it's an anonymous inner class (See Java tutorial documentation)

But there is more complex solution involving bytecode weaving libraries. Libraries such as cglib, asm, javassist etc. give you a facility to dynamically create new classes at runtime and load them.

Javassist has a tutorial on how to add methods to classes at runtime. It should be possible to adapt it to add/override the method, something like this:

CtClass origClazz = ClassPool.getDefault().get("org.example.MyObject");
CtClass subClass = ClassPool.getDefault().makeClass(cls.getName() + "New", origClazz);
CtMethod m = CtNewMethod.make(
             "public void setBar(String bar) { this.bar = bar; }",
             subClass );
subClass .addMethod(m);
Class clazz = cc.toClass();

If you're returning an object of an interface type, you can use Proxy.newProxyInstance to get an instance of an interface that dynamically sends method invocations to an InvocationHandler object which you can write to do whatever custom behavior you want.

No, what you are asking for is something like runtime compilation. While not impossible it certainly isn't something that the reflection API provides.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!