测试类
package org.example.bytebuddy;
public class Log {
public void print(String message){
System.out.println(message);
}
}
复写class并拦截请求
package org.example;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.matcher.ElementMatchers;
import org.example.bytebuddy.Log;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.Callable;
public class Main {
static {
Instrumentation instrumentation = ByteBuddyAgent.install();
// new ByteBuddy().redefine(Log.class).method(ElementMatchers.named("print")
// .and(ElementMatchers.takesArgument(0,String.class)))
// .intercept(MethodDelegation.to(LogDelegate.class))
// .make()
// .load(Log.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
// REBASE 复制后修改 允许新增、删除方法 性能较低 REDEFINITION 直接修改 不允许新增、删除方法 性能高
new AgentBuilder.Default().with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.with(AgentBuilder.RedefinitionStrategy.REDEFINITION).type(ElementMatchers.named("org.example.bytebuddy.Log"))
.transform((builder, typeDescription, classLoader,
javaModule, protectionDomain) ->
builder.method(ElementMatchers.named("print").and(ElementMatchers.takesArgument(0,String.class))
.and(ElementMatchers.returns(void.class))).intercept(
MethodDelegation.to(LogDelegate.class)
)
).installOn(instrumentation);
}
public static void main(String[] args) {
new Log().print("Hello World");
new Log().print("haha");
}
public static class LogDelegate{
@RuntimeType
public static void intercept(@AllArguments Object[] args, @SuperCall Callable<Void> superCall) {
String arg = (String) args[0];
System.out.println("hello" + arg);
try {
superCall.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}