views:

317

answers:

4

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.

+2  A: 

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

Peter Štibraný
Just be careful with Enhancer, because it has a seriously confused delusion about the difference between delegation and inheritance. For example, you'd better hope that the "enhanced" class doesn't invoke any instance methods in its constructor.
erickson
+5  A: 

Look into Dynamic Proxy classes.

Hank Gay
This works with interfaces only, afaik.
Peter Štibraný
I don't see how this is the correct answer. It only works with interfaces which means you are not overriding (i.e. an existing) method. Sounds like aspects are the only reasonable approach.
Robin
He's probably already using interfaces, so he can use Dynamic Proxy classes to change the behavior he wants to change and delegate to an implementation the behavior he doesn't want to change.
Hank Gay
+3  A: 

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.

duffymo
+3  A: 

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.

Tom Hawtin - tackline