I got many similar questions on SO but still trying to figure out if we can replace a method body at runtime and can that modified method be executed by the existing invocations to that method.
After reading many answers to similar questions, I learned that we can replace any user defined class at runtime. Then we can load the modified class (e.g., there is a modified method in the modified class), create an instance of that class, and invoke the modified method. The accepted answer to the this question was very helpful for me to understand the concept.
Basically the example used in that answer explains that if we change Test1.hello()
, that would be picked by the main
method in Test
class since it is creating a new instance of Test1
class and invoking hello through that instance.
Class cls = new TestClassLoader().loadClass("test.Test1");
Object obj = cls.newInstance();
cls.getMethod("hello").invoke(obj);
But there can be situations, where there are many existing calls to hello()
in the code base (e.g., in Test2.java
), and we want that after we load the the Test1
class dynamically, all the existing invocations in Test2
would execute the modified method, not the old one.
I was wondering if it is possible at all, or if I am missing something.
Thanks much in advance.
Aucun commentaire:
Enregistrer un commentaire