Tuesday, 5 May 2020

Javassist: Replace content of a method at run time

Follow below steps to replace the content of a method.

 

Step 1: Get instance of ClassPool

ClassPool classPool = ClassPool.getDefault();

 

Step 2: Get CtClass instance for given class.   

CtClass ctClass = classPool.get("com.sample.app.Welcome");

 

Step 3: Get CtMethod instance for the method that you want to update the body

CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello");

 

Step 4: Set new body to the method.

ctMethod.setBody("{ return \"Hello from javassist\"; }");

 

Step 5: Call toClass method to reflect new byte code changes.

ctClass.toClass();

 

Step 6: Create new instance of Welcome class and test it.

Welcome welcomeAfterUdateBody = new Welcome();

String msg = welcomeAfterUdateBody.sayHello();

 

Find the below working application.

 

Welcome.java
package com.sample.app;

public class Welcome {
	
	public String sayHello() {
		return "Hello!!!!";
	}

}

App.java

package com.sample.app;

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

public class App {

	public static void main(String args[]) throws Exception {

		ClassPool classPool = ClassPool.getDefault();

		CtClass ctClass = classPool.get("com.sample.app.Welcome");
		CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello");
		ctMethod.setBody("{ return \"Hello from javassist\"; }");

		ctClass.toClass();

		Welcome welcomeAfterUdateBody = new Welcome();
		String msg = welcomeAfterUdateBody.sayHello();
		System.out.println(msg);

	}
}

Run App.java, you will get below message in console.

 

Hello from javassist


Previous                                                    Next                                                    Home

No comments:

Post a Comment