簡體   English   中英

Bytebuddy:是否可以通過用 lambda 表達式替換執行來攔截方法?

[英]Bytebuddy: Is it possible to intercept a method by replacing the execution with a lambda expression?

是否可以通過用 lambda 表達式或其他 class 的非靜態方法替換執行來攔截方法?

例 1:

installByteBuddyAgent();

byteBuddy
        .redefine(sourceClass) //This is important, i need to change a class definition
        .method(named(methodName))
        .intercept({{expression}})
        .make()
        .load(
                sourceClass.getClassLoader(),
                ClassReloadingStrategy.fromInstalledAgent());

//expression = Lambda expression that would be executed in place of the original method, or call a (non-static) method from some other class.

目的是避免使用 static 方法編寫 class 來執行攔截。

例 2:

    public class A {
        public void sayHello() {
            System.out.println("Hello");
        }
    }

    public class B {
        public void sayGoodbye() {
            System.out.println("Goodbye");
        }
    }
    
// ...

    @Test
    void interceptAReplacingByB() {
        final Class<A> sourceClass = A.class;
        final B b = Mockito.spy(new B());
        
        byteBuddy
                .redefine(sourceClass)
                .method(named("sayHello"))
                .intercept( /*call sayGoodbye from B or create a lambda expression to do it*/ )
                .make()
                .load(
                        sourceClass.getClassLoader(),
                        ClassReloadingStrategy.fromInstalledAgent());
        
        new A().sayHello();
        
        Mockito.verify(b).sayGoodbye();
    }

此代碼片段並不代表完整的場景。 它只是為了舉例說明這個問題。

公共方法的攔截可以通過其他方式完成,但目標不是只與公共方法一起工作,或者只與測試場景一起工作。

如果我的解釋是正確的:

// ...
.intercept(net.bytebuddy.implementation.MethodCall.invoke("sayGoodbye").on(b))
// ...

請注意, 在重新實現A時將定義一個static字段來保存b的實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM