Interposing on Java Class Methods (without interfaces)
Asked Answered
L

1

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.

Livonia answered 30/1, 2012 at 9:4 Comment(3)
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.Remembrance
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?Accept
Sometimes, hacking is the only way to do it. If you're interested in the (long) story, send me a PM =)Livonia
R
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

Rufena answered 30/1, 2012 at 9:10 Comment(1)
I forget to precise it was related to Android. Is AspectJ compatible with Android ?Livonia

© 2022 - 2024 — McMap. All rights reserved.