Hai every body, topic discussing today is Dynamic Code Injection. Before getting into this,lets have a small demo. Please excuse me, most of you guys get bored because,its nothing but a very orthodox java program written using Eclipse IDE.
Lets have look on this.
Here we are having two java classes. Greetings.java and Main.java.
Lets look inside Greeting.java.
Here you can see a method ask().What is written inside ask().Its nothing but a console print statement "WHO AM I ? ". You can see nothing other than this. Now lets look what isin Main.java.
It has one main method in which we are instantiating Greeting.java and invoking ask() method.
Now guess, what is the out put of this program? Yes we expect, WHO ARE YOU-? will be appear on the console.Ok lets check the output. After running the program, output appear like this
Surprised!!!!!? Our expectation was "WHO AM I ? " but Actual is "WHO AM I ? YOU ARE A FOOL".
How system automatically recognized you? Just kidding. Expected output was WHO AM I ? . because we only written code for this. But actual result contains something more. Then its time to ask, how this happens? Now we are in a position to discuss What? How?
What is dynamic code injection?
Dynamic code injection is the technique of injecting code in our original code while application runs. In this way we can alter the behavior of the class or objects at any moment we wants. So that we can bring polymorphic behavior to our object depending up on the context.
How we can achieve this?
This is not a new thing. It is their in Java since 1.5. You can refer java.lang.instrument package for more details. This package provide services that allow java programming language agent to instrument programs running on the jvm. Actually we are altering the byte code of the methods. The changes made to the code are purely additive, so these techniques do not modify application state or behavior.
Example usage of this
* Monitoring Agents
* Profilers,
* Code Coverage Analyser
* Mocking Test Cases
* Event Loggers Etc.