Make delicious recipes!

Inserting code at runtime using Javassist byte-code editor

Following code shows how to insert code dynamically before loading its class:
<project xmlns="" xmlns:xsi=""





package com.prismoskills.javassist.examples.annotation;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

 * Example showing how to dynamically insert code using Javassist byte-code editor
public class DynamicCodeInsertion
    static String pkgName = "com.prismoskills.javassist.examples.annotation";
    public static void main(String[] args) throws Exception
        ClassPool cp = ClassPool.getDefault();
        CtClass cc = cp.get(pkgName + ".FooCodeInsertion");
        // Without the call to "makePackage()", package information is lost
        cp.makePackage(cp.getClassLoader(), pkgName);
        CtMethod m = cc.getDeclaredMethod("helloWorld");
        m.insertBefore("{System.out.print(\"Oh, say no to \");}");
        m.insertAfter("{System.out.print(\"And say - Hi World\");}");
        // Changes are not persisted without a call to "toClass()"

        (new FooCodeInsertion()).helloWorld();


class FooCodeInsertion
    public void helloWorld ()
        System.out.println ("Hello World");

Output for the above is:
Oh, say no to Hello World
And say - Hi World

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal