In Java, given an object, is it possible to override one of the methods?

别来无恙 提交于 2019-12-23 18:00:05

问题


I have an object of class A. I want to override one of the methods of that class. Can this be done?

More specifically, I have an object that is being injected into a field. I need to override one of the methods, before I can use it.

I am trying to see if Reflection could help solve the problem. Note that the method that I am trying override does not dependent on private variables of that class.


回答1:


Look into Dynamic Proxy classes.




回答2:


Yes.

Overriding means writing a new class, compiling it, changing the injection to use the new class, and packaging it with the rest of your app. Of course it can be done, but I don't see why you'd want reflection.

If you want this to be a dynamic thing, you're talking about aspect-oriented programming.




回答3:


Assuming you are being given the object and so cannot subclass it: You can write a proxy. Forward on all the methods as is with the exception of the one you want to override. Of course no other reference to that original object will use the proxy. In particular if the object itself internally calls methods on itself then that will not use the "overridden" method.

Alternatively you could rewrite the code that calls the method, or modifies the implementing class, using AOP-style hacks.

Probably you want to have a careful think about your design.




回答4:


CGLIB should be able to help you to achieve what you're trying to do. Check out Enhancer class.



来源:https://stackoverflow.com/questions/631361/in-java-given-an-object-is-it-possible-to-override-one-of-the-methods

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