<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.27.0-GA</version>
</dependency>
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
public class LoggingAspect {
public static void logBeforeMethod(Object[] args) {
System.out.println("Before method execution: " + args[0]);
}
public static void logAfterMethod(Object returnValue) {
System.out.println("After method execution: " + returnValue);
}
public static void applyAspect(Class<?> targetClass) throws Exception {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get(targetClass.getName());
CtMethod targetMethod = ctClass.getDeclaredMethod("targetMethod");
CtMethod copiedMethod = CtNewMethod.copy(targetMethod, targetMethod.getName() + "$original", ctClass, null);
targetMethod.setBody("{" +
"LoggingAspect.logBeforeMethod($args);" +
"Object result = " + copiedMethod.getName() + "($$);" +
"LoggingAspect.logAfterMethod(result);" +
"return result;" +
"}");
ctClass.addMethod(copiedMethod);
targetClass.getDeclaredMethod("targetMethod").invoke(null);
byte[] modifiedClass = ctClass.toBytecode();
targetClass.getClassLoader().defineClass(targetClass.getName(), modifiedClass);
}
}
public class TargetClass {
public static void targetMethod() {
System.out.println("Executing targetMethod...");
}
}
public class MainClass {
public static void main(String[] args) throws Exception {
LoggingAspect.applyAspect(TargetClass.class);
}
}
Before method execution: null
Executing targetMethod...
After method execution: null