You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Byte Buddy @Super注解泛化拦截及子类转发父类方法的技术咨询

关于Byte Buddy与Minecraft Mixin的问题解答

1. 泛化@Super注解拦截任意方法

Byte Buddy的@Super注解默认仅在重写方法的拦截场景生效,若要拦截任意方法并实现类似@Super的父类方法调用效果,可通过批量方法匹配结合SuperMethodCall实现:

  • 用ElementMatchers.any()匹配所有目标方法
  • 拦截逻辑中通过MethodDelegation自定义处理逻辑,再拼接SuperMethodCall.INSTANCE调用父类对应方法,等价于泛化的@Super用法
  • 示例代码:
new ByteBuddy()
  .subclass(TargetClass.class)
  .method(ElementMatchers.any())
  .intercept(MethodDelegation.to(CustomInterceptor.class)
    .andThen(SuperMethodCall.INSTANCE))
  .make();

2. 访问子类父类实例属性并转发参数

分两步解决:

  • 访问父类实例字段:在拦截器中用@FieldValue注解直接注入子类中持有的父类实例字段(需知晓字段名称,比如delegate):
    public class ForwardingInterceptor {
      public static Object forward(@FieldValue("delegate") Object parentInstance,
                                  @Origin Method method,
                                  @AllArguments Object[] args) throws Exception {
        return method.invoke(parentInstance, args);
      }
    }
    
  • 参数转发:@AllArguments会自动将方法参数打包为数组,直接传入method.invoke()即可完成转发,Byte Buddy会自动处理原始类型的装箱/拆箱,无需手动解包。

3. 处理Minecraft类的批量方法重写

Byte Buddy完全适合这类批量处理场景,无需手动重写100+方法:

  • 用ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class))排除Object类通用方法(如toString、hashCode),仅匹配目标类的自定义方法
  • 通过subclass()结合批量拦截逻辑,一次性生成所有方法的转发代码
  • 若已使用Minecraft Mixin,可结合两者:用Mixin创建子类,再用Byte Buddy处理批量转发;或直接在Mixin中用@Redirect实现,但Byte Buddy在批量方法处理上更简洁
  • 示例代码:
Class<?> dynamicSubclass = new ByteBuddy()
  .subclass(MinecraftTargetClass.class)
  .defineField("delegate", MinecraftTargetClass.class, Modifier.PRIVATE | Modifier.FINAL)
  .constructor(ElementMatchers.any())
  .intercept(FieldAccessor.ofField("delegate").setsArgumentAt(0))
  .method(ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class)))
  .intercept(MethodDelegation.to(ForwardingInterceptor.class))
  .make()
  .load(ClassLoader.getSystemClassLoader())
  .getLoaded();

内容的提问来源于stack exchange,提问作者Pixirora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:50:46