Skip to content

Instantly share code, notes, and snippets.

@bric3
Last active July 25, 2016 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bric3/b6a04fa7823c376eaad31cf8a2799d2b to your computer and use it in GitHub Desktop.
Save bric3/b6a04fa7823c376eaad31cf8a2799d2b to your computer and use it in GitHub Desktop.
package bob.yop;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.nameContains;
import static net.bytebuddy.matcher.ElementMatchers.named;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import org.apache.kafka.common.network.NetworkReceive;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.implementation.bind.annotation.FieldValue;
import net.bytebuddy.implementation.bind.annotation.Origin;
public class InstrumentationTest {
public static void initialize() {
new AgentBuilder.Default()
.type(named("bob.yop.InstrumentationTest$Foo").or(nameContains("NetworkReceive")))
.transform((builder, typeDescription, classLoader) -> builder
// cannot work because new Object() { ... } is not visible to NetworkReceive
// .constructor(any()).intercept(to(new Object() {
// public void construct(@AllArguments Object[] parameters, @Origin Class<?> type) throws Exception {
// System.out.format("%s.<cinit>%n", type.getSimpleName());
// }
// }).andThen(SuperMethodCall.INSTANCE))
.method(named("foo").or(named("complete")))
.intercept(to(ReadFieldOnMethod.class).andThen(SuperMethodCall.INSTANCE)))
.installOn(ByteBuddyAgent.install());
}
public static void main(String[] args) {
initialize();
new NetworkReceive().complete();
Foo foo = new Foo();
System.out.println(foo.foo(1, 5));
}
private static class Foo {
ByteBuffer size;
public Foo() {
this("a", 1);
}
public Foo(String a, int i) {
size = ByteBuffer.allocate(4);
}
public int foo(int a, int b) {
return a + b;
}
}
public static class ReadFieldOnMethod {
public static void logFieldValue(@Origin Method method, @FieldValue("size") ByteBuffer size) {
System.out.format("'%s.%s', size=%d%n", method.getDeclaringClass().getSimpleName(), method.getName(), size.getInt());
size.rewind();
}
}
}
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.4.14</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.9.0.1</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment