Follow below steps to add and invoke new method.
Step 1: Get an object of ClassPool.
ClassPool classPool = ClassPool.getDefault();
Step 2: Get CtClass object for given class.
CtClass ctClass = classPool.get("com.sample.app.Test");
Step 3: Define and add new method to CtClass instance.
CtMethod newmethod = CtNewMethod.make("public void print() { System.out.println(\"Hey are you there\"); }",ctClass);
ctClass.addMethod(newmethod);
Step 4: Publish byte code changes.
ctClass.toClass();
Step 5: Call the added method using reflection.
Test test = new Test();
Method method = test.getClass().getMethod("print", new Class[] {});
method.invoke(test, new Object[] {});
Find the below working application.
package com.sample.app;
public class Test {
}
App.java
package com.sample.app;
import java.lang.reflect.Method;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
public class App {
public static void main(String args[]) throws Exception {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get("com.sample.app.Test");
CtMethod newmethod = CtNewMethod.make("public void print() { System.out.println(\"Hey are you there\"); }",
ctClass);
ctClass.addMethod(newmethod);
ctClass.toClass();
Test test = new Test();
Method method = test.getClass().getMethod("print", new Class[] {});
method.invoke(test, new Object[] {});
}
}
Run App.java, you will get below message in console.
Hey are you there
No comments:
Post a Comment