public class CustomClassLoader extends ClassLoader {
public Class defineClass(String className, byte[] byteCode) {
return defineClass(className, byteCode, 0, byteCode.length);
}
}
public static void enhanceMethod(CtMethod method) throws CannotCompileException {
method.addLocalVariable("startTime", CtClass.longType);
method.insertBefore("startTime = System.currentTimeMillis();");
method.insertAfter("System.out.println(\"Method execution time: \" + (System.currentTimeMillis() - startTime) + \"ms\");");
}
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
public class JavassistExample {
public static void main(String[] args) throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass targetClass = pool.get("com.example.TargetClass");
CtMethod targetMethod = targetClass.getDeclaredMethod("targetMethod");
enhanceMethod(targetMethod);
CustomClassLoader loader = new CustomClassLoader();
Class enhancedClass = loader.defineClass(targetClass.getName(), targetClass.toBytecode());
Object enhancedObject = enhancedClass.newInstance();
enhancedClass.getMethod("targetMethod").invoke(enhancedObject);
}
public static void enhanceMethod(CtMethod method) throws Exception {
method.addLocalVariable("startTime", CtClass.longType);
method.insertBefore("startTime = System.currentTimeMillis();");
method.insertAfter("System.out.println(\"Method execution time: \" + (System.currentTimeMillis() - startTime) + \"ms\");");
}
}