How to inject code at runtime in Java?
UPDATED: 01 November 2014
Tags:
bytecode
,
Reflection
Its been never easy for me to believe that you can inject code into existing method without changing its original code but this can also happens using library javassist.
javassist
Javassist (Java Programming Assistant) allows you to manipulate bytecode. It enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Read more about plug-in on http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/.
Shigeru Chiba originally created this library now its sub project of Jboss organization. You can read more about author on his blog http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/site/.
Source code background
We created two class files 1. SampleCodeJavassist and 2. CommonUtil under package javaQuery.javassist. You can have your own package name.
Source Code
package javaQuery.javassist; public class CommonUtil { public void printToConsole() { System.out.println("javaQuery"); } }
/** * @author javaQuery */ package javaQuery.javassist; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; public class SampleCodeJavassist { public static void main(String[] args) throws Exception { /* Create object of ClassPool */ ClassPool objClassPool = ClassPool.getDefault(); /** * Create an object of CtClass. * Get the instance of class you want to inject the code. * Be careful while accessing the class. You have to specify whole the package name. */ CtClass objCtClass = objClassPool.get("javaQuery.javassist.CommonUtil"); /** * Create an object of CtMethod. * Get the method where you want to inject the code. */ CtMethod objCtMethod = objCtClass.getDeclaredMethod("printToConsole"); /* Inject the code at the begging of the method */ objCtMethod.insertBefore("{ System.out.println(\"Hello World! at the beggining of method [Runtime from Test class]\"); }"); /* Inject the code at the end of the method */ objCtMethod.insertAfter("{ System.out.println(\"Hello World! at the end of method [Runtime from Test class]\"); }"); /* Create an object of Class */ Class objClass = objCtClass.toClass(); /* Create an instance of CommonUtil class using objClass */ CommonUtil objCommonUtil = (CommonUtil)objClass.newInstance(); /* Execute method printToConsole */ objCommonUtil.printToConsole(); } } //output Hello World! at the beggining of method [Runtime from Test class] javaQuery Hello World! at the end of method [Runtime from Test class]This article is just to give you basic information of plug-in. Read more about plug-in on official website http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/.
Tags:
bytecode
,
Reflection
0 comments :