使用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
相关产品推荐
相关产品推荐

