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

使用Byte Buddy为类添加方法时遇VerifyError问题求助

解决Java Agent添加方法时的VerifyError: Local variable table overflow问题

问题原因分析

你遇到的错误核心在于静态方法和实例方法的局部变量表差异:

  • 目标类的method1是静态方法,这类方法的局部变量表中不存在this引用(局部变量索引0不会指向任何实例)。
  • 你通过Agent给Method类添加的method3默认是实例方法(没有指定static修饰符),当你在静态的method1拦截逻辑里调用这个实例方法时,字节码会自动生成aload_0指令试图加载this,但静态方法里根本没有这个局部变量,直接触发了JVM的字节码验证错误。

解决方案:将添加的method3改为静态方法

只需要在Agent定义方法时,给method3加上static修饰符,让它和method1保持一致的静态属性,这样调用时就不需要this引用了。

修改后的Agent代码:

new AgentBuilder.Default()
    .with(AgentBuilder.Listener.StreamWriting.toSystemError())
    .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
    .type(ElementMatchers.nameContains("Method"))
    .transform((builder, typeDescription, classLoader, module) -> builder
        // 定义静态的method3,关键是加上withModifiers(Modifier.STATIC)
        .defineMethod("method3", void.class, Visibility.PUBLIC)
        .withModifiers(Modifier.STATIC)
        .intercept(MethodDelegation.to(AddMethod.class))
        .method(ElementMatchers.nameContains("method1"))
        .intercept(SuperMethodCall.INSTANCE
            .andThen(MethodCall.invoke(ElementMatchers.named("method3"))))
).installOn(instrumentation);

额外说明

  • 你的AddMethod类中的method3已经是静态方法,不需要做任何修改,和Agent中定义的静态method3匹配度完美。
  • 如果非要把method3做成实例方法,那在静态的method1里调用它时必须先获取Method类的实例,但静态方法本身没有关联实例,这种场景下逻辑上并不合理,所以优先推荐上面的静态方法方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:50:55