import javassist.*; public class DynamicModificationDemo { public static void main(String[] args) throws Exception { ClassPool classPool = ClassPool.getDefault(); CtClass targetClass = classPool.get("com.example.TargetClass"); CtMethod targetMethod = targetClass.getDeclaredMethod("targetMethod"); targetMethod.insertBefore("{ System.out.println(\"Before method execution\"); }"); targetMethod.insertAfter("{ System.out.println(\"After method execution\"); }"); byte[] modifiedClassBytes = targetClass.toBytecode(); Class modifiedClass = classPool.makeClass(new ByteArrayInputStream(modifiedClassBytes)).toClass(); Object modifiedInstance = modifiedClass.newInstance(); modifiedInstance.getClass().getMethod("targetMethod").invoke(modifiedInstance); } }


上一篇:
下一篇:
切换中文