bytebuddy使用

測試類

package org.example.bytebuddy;

public class Log {

    public void print(String message){
        System.out.println(message);
    }
}

復(fù)寫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  復(fù)制后修改 允許新增、刪除方法 性能較低  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);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容