【问题标题】:How to intercept a method of an existing class and delegate all calls to a different implementation of the interface using byte-buddy如何拦截现有类的方法并使用字节伙伴将所有调用委托给接口的不同实现
【发布时间】:2021-07-13 04:19:30
【问题描述】:

我是 byte-buddy 的新手,我正在尝试使用它在我的项目中构建解决方案。对于特定场景,我不知道如何实施该解决方案。

我有 2 个接口(或父类的子类)的实现

基于一个条件,我想将 Class1 的所有方法调用委托给 Class2。

例子:

public class Class1 implements SampleInterface{

public Map<String,String> operation1(List<String> var){
}

public void operation2(List<String> var){}

public void operation3(){
   System.out.println("Class1 :  Operation 3");
}
}
public class Class2 implements SampleInterface{

public Map<String,String> operation1(List<String> var){
}

public void operation2(List<String> var){}

public void operation3(){
   System.out.println("Class1 : Operation 3");
}
}

我想使用 byte-buddy 重新定义 Class1,如下所示。 我想将 Class2 的实例注入 Class1。 条件子句需要放在每个方法中。

有人可以帮忙解答吗?

public class Class1 implements SampleInterface{

Class2 proxyInstance;

public Map<String,String> operation1(List<String> var){
   if(condition==true){
      return proxyInstance.operation1(var);
   }else{
      //Class1 implementation
   }
}

public void operation2(List<String> var){
   if(condition==true){
      return proxyInstance.operation2(var);
   }else{
      //Class1 implementation
   }

}

public void operation3(){
   if(condition==true){
     proxyInstance.operation3();
   }else{
      System.out.println("Class1 :  Operation 3");
   }
 }
}

【问题讨论】:

    标签: byte-buddy


    【解决方案1】:

    我可以通过混合 javassit 和 byte-buddy 来实现我想要的解决方案。我可以通过这个实现实现以下目标

    1. 无需在命令行中附加 -javaagent 即可进行检测
    2. 我可以在一个 jar 下包含多个代理,并根据需要从 main 方法调用它们。
    3. 我可以更改方法的行为并在类级别添加新字段。

    虽然我的问题没有得到任何回应,但学习这个主题的各个方面并达到我可以按要求实施解决方案的地步是很好的体验

    【讨论】:

      【解决方案2】:

      使用 Byte Buddy,您应该可以为此使用 MethodDelegation。您可以通过声明参数@Origin Method m@AllArguments Object[] args 的参数来获取原始方法。然后,您可以使用它来调用委托实例上的方法或调度您的自定义逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-18
        • 2021-02-26
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 2013-03-22
        • 2023-03-29
        • 2011-05-31
        相关资源
        最近更新 更多