1

I'd like to interpose between class methods to dynamically extends an object.

I already know about the java.lang.reflect.Proxy stuff, but it's way too limited to do real interposing.

From Using java.lang.reflect.Proxy to Interpose on Java Class Methods, the first limitation is :

(...) the method must be called through an instance of the proxy class. So nested methods calls, for instance, would not be intercepted.

And the worst one :

(...) the method must have been defined in an Interface that is implemented by the object being proxied. It can not be called through an instance of a class that does not implement an interface.

The object I'd like to extends at run-time doesn't implement any interface, and worst, the methods I need to override are nested and private.

I know this is fairly easy in Python & C, and the article cited above says that it could be possible :

The next article in this series will illustrate some techniques for overcoming these limitations.

Unfortunately, I'm unable to find this article.

Mark Cramer
  • 2,614
  • 5
  • 33
  • 57
Renaud Cerrato
  • 1,297
  • 16
  • 20
  • 4
    That article is from 2001. It's *11 years old*. You may want to try and find something less prehistoric to base your experiments on. – skaffman Jan 30 '12 at 09:15
  • 2
    This sort of changes are usually considered very bad programming practices. It can lead to unmaintainable and unsupportable code. What you suggest usually has a better way of being done. I suspect you have a particular solution to a problem in mind. Would you consider other solutions to the same problem? – Peter Lawrey Jan 30 '12 at 09:24
  • Sometimes, hacking is the only way to do it. If you're interested in the (long) story, send me a PM =) – Renaud Cerrato Jan 30 '12 at 13:09

1 Answers1

3

Try using CGLIB:

Here is a tutorial I wrote a couple of years ago, its quite simple introduction to CGLIB: CGLIB intro

If you need even more power, consider to use AspectJ

Hope this helps

Community
  • 1
  • 1
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97