我可以使用 Byte Buddy 从父 class 重新定义私有方法吗?

Can I redefine a private method from a parent class using Byte Buddy?

基于Can I redefine private methods using Byte Buddy?的想法,我想重新定义一个父类的私有方法class。 那可能吗?或者就像先有鸡还是先有蛋的问题?

谢谢!

实际上不调度私有方法,因此,您不能在子class中更改私有方法的调度。这样做的唯一方法是直接将条件分派硬编码到私有方法中。

您可以这样做,方法是将 Byte Buddy 的 Advice class 与 Java 代理结合使用。 Java 代理如下所示:

new AgentBuilder.Default()
  .disableClassFormatChanges()
  .with(RedefinitionStrategy.REDEFINITION)
  .type(is(ClassWithPrivateMethod.class))
  .transform((builder, type, cl, module) -> {
     return builder.visitor(Advice.to(MyAdvice.class)
                                  .on(named("privateMethod")));
   }).install(inst);

其中 MyAdvice 的代码内联在名为 privateMethod 的方法的开头。条件调度如下所示:

class Adv {
  @OnMethodEnter(skipOn = OnNonDefaultValue.class)
  static boolean intercept(@This ClassWithPrivateMethod self) {
    if (self instanceof ParentClass) {
      // Your code
      return true;
    } else {
      return false;
    }
  }
}

通过返回 true 和使用跳过条件,如果返回 false 则仅执行实际代码。