In pure Java, using intrumentation and java agents, there is a way to replace the body of a method at runtime.
Unfrotunately java.lang.instrument.Instrumentation
is not available under Android.
I have checked all other alternatives, like the one described here in stackoverflow, which directs to the obsolete javassist-android implementation. Which surprisingly works, but only for new classes.
There's also an article named Hot swapping code in Android which describes how again to load classes at runtime, not how to replace existing methods of classes.
The only article dealing with this issue is an article named Android hacking: replacing system classes methods with your own, which misses the source code and refers to Dalvik, not ART (so it won't work on modern hardware).
So, is there any way to do so?
...
Bottom line: the reason I want this is to trace specific method calls in my application, like just when this method is called (and do some action before it) and just when this method exits (and also do some action on it). These methods are defined at runtime, so there's no way to know them in advance, at compile time.
Although the j.l.instrument APIs were never added to android the underlying JVMTI apis that were used to implement them were added in Android O. For example here is a test JVMTI agent that will redefine listed classes and add a single nop to the beginning of every method: https://android.googlesource.com/platform/art/+/refs/heads/master/tools/jvmti-agents/simple-force-redefine/