3

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.

Vijay Kotari
  • 1,945
  • 3
  • 15
  • 16

4 Answers4

5

Look into Dynamic Proxy classes.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
  • 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 Mar 10 '09 at 18:07
  • 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 Mar 10 '09 at 18:48
3

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

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
  • 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 Mar 10 '09 at 17:24
3

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
  • 305,152
  • 44
  • 369
  • 561
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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305