6. Agenda
The use cases for bytecode manipulation
Code examples with Javassist
How to create your own Java agent
speakerdeck.com/antonarhipov
github.com/zeroturnaround/callspy
9. Bytecode manipulation
Main use case for Javassist: generate proxies
i.e.at runtime,create a subclass that intercepts
all method invocations
Spring AOP
Hibernate proxies EJB proxies
CDI proxies
java.lang.reflect.Proxy is not enough
17. Javassist
Bytecode manipulation made easy
Source level and bytecode level APIs
Uses vocabulary of a Java language
On-the-fly compilation of injected code
www.javassist.org
23. public static void premain(String args,
Instrumentation inst)
java -javaagent:<jarfile>[=options]
META-INF/MANIFEST.MF is required
24. public static void agentmain(String args,
Instrumentation inst)
Executed when the agent attaches to the running JVM
META-INF/MANIFEST.MF is required
Requires support for loading agents in JVM
Allows adding the code to JVM post-factum
26. import com.sun.tools.attach.VirtualMachine;
//attach to target VM
VirtualMachine vm = VirtualMachine.attach("2177");
//get system properties in the target VM
Properties props = vm.getSystemProperties();
//load agent into the VM
vm.loadAgent("agent.jar", "arg1=x,arg2=y");
//detach from VM
vm.detach();
http://docs.oracle.com/javase/7/docs/jdk/api/attach/spec/com/sun/tools/attach/VirtualMachine.html