Using a Java library called Javassist it is possible to create class files on the fly and use them in the same program that created them. Sounds funky, and it is…

First download the jar file from the JBoss download website. Then write a sample class file that will be edited by the Javassist library in a later stage:

package com.example;

public class HelloWorld {

    public void sayHello() {
        // No content yet
    }
}

This class HelloWorld has a single public method sayHello, which does nothing at the moment. Now write another class that takes the Javassist library and alters this:

package com.example;

import static javassist.ClassPool.getDefault;
import java.io.IOException;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class JavaAssistTest {

    public static void main(String[] args) {
        try {
            CtClass ctClass = getDefault().get("com.example.HelloWorld");
            CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello");
            ctMethod.setBody("{ System.out.println("Hello World Modified"); }");
            ctClass.writeFile("bin");

            HelloWorld helloWorld = new HelloWorld();
            helloWorld.sayHello();
        } catch (NotFoundException | CannotCompileException | IOException e) {
            e.printStackTrace();
        }
    }
}

This class loads the HelloWorld class, takes its sayHello method and sets a new implementation. In this example it adds a call to System.out with an appropriate text. It then writes the new implementation to file, in the bin directory. Directly after this, it creates a new object of the class HelloWorld and calls its sayHello method. And yes, it now prints:

Hello World Modified
Running dynamic Java code
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *