Created
February 23, 2015 14:11
-
-
Save raphw/2c1d71417ddb50f14cea to your computer and use it in GitHub Desktop.
Byte Buddy agent: JDK 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package introspect; | |
import net.bytebuddy.instrumentation.method.bytecode.bind.annotation.AllArguments; | |
import net.bytebuddy.instrumentation.method.bytecode.bind.annotation.Origin; | |
import java.lang.reflect.Method; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class LogInterceptor { | |
public static AtomicInteger counter = new AtomicInteger(); | |
public static void log(@AllArguments Object[] allArguments, @Origin Method method) { | |
counter.addAndGet(1); | |
for (int i = 0; i < allArguments.length; i++) { | |
System.out.println(allArguments[i]); | |
} | |
System.out.println("Called on:" + method.getDeclaringClass().toString()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package introspect; | |
import net.bytebuddy.agent.ByteBuddyAgent; | |
import net.bytebuddy.agent.builder.AgentBuilder; | |
import net.bytebuddy.dynamic.DynamicType; | |
import net.bytebuddy.instrumentation.MethodDelegation; | |
import net.bytebuddy.instrumentation.SuperMethodCall; | |
import net.bytebuddy.matcher.ElementMatchers; | |
import java.lang.instrument.Instrumentation; | |
public class MainTest { | |
public static void initialize(String name, Instrumentation inst) { | |
new AgentBuilder.Default() | |
.rebase(ElementMatchers.nameContains(name) | |
.and(ElementMatchers.not(ElementMatchers.nameContains("LogInterceptor"))) | |
.and(ElementMatchers.not(ElementMatchers.nameContains("load"))) | |
.and(ElementMatchers.not(ElementMatchers.nameContains("init"))) | |
).transform(new AgentBuilder.Transformer() { | |
@Override | |
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder) { | |
return builder | |
.method(ElementMatchers.any()) | |
.intercept(MethodDelegation.to(LogInterceptor.class).andThen(SuperMethodCall.INSTANCE)); | |
} | |
}).installOn(inst); | |
} | |
public static void main(String[] args) { | |
initialize("introspect", ByteBuddyAgent.installOnOpenJDK()); | |
Foo foo = new Foo(); | |
System.out.println(foo.foo(1, 5)); | |
} | |
private static class Foo { | |
public int foo(int a, int b) { | |
return a + b; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment