使用字节好友向类添加方法



我正在尝试使用 Java 代理向类添加一个方法。但它给出了如下错误。

java.lang.VerifyError: Local variable table overflow 

Exception Details:
  Location:com/github/shehanperera/example/Method.method1()V @3: aload_0
  Reason: Local index 0 is invalid
  Bytecode: 0x0000000: b800 532a b600 56b1            
    at com.github.shehanperera.example.Sample.main(Sample.java:13)

这是我的经纪人

new AgentBuilder.Default()
            .with(AgentBuilder.Listener.StreamWriting.toSystemError())
            .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
            .type((ElementMatchers.nameContains("Method")))
            .transform((builder, typeDescription, classLoader, module) -> builder
                    .defineMethod("method3", void.class, Visibility.PUBLIC)
                    .intercept(MethodDelegation.to(AddMethod.class))
                    .method(ElementMatchers.nameContains("method1"))
                    .intercept(SuperMethodCall.INSTANCE
                            .andThen(MethodCall.invoke(ElementMatchers.nameContains("method3"))))
            ).installOn(instrumentation);

这是我需要添加的方法.

public class AddMethod {
public static void method3() throws Exception {
    System.out.println("This is new method : method 3");
}}

这是我真正的方法类,我想在其中添加新方法。

public class Method {
Method() {
    System.out.println("This is constructor ");
}
public static void method1() {
    try {
        Thread.sleep(500);
        System.out.println("This is Method 1");
    } catch (InterruptedException e) {
        //Ignore
    }
}}

这是主要方法

public static void main(String[] args) {
    System.out.println("This is Sample main");
   (13) Method method = new Method();
    method.method1();
}

你能告诉我在这种情况下有什么问题吗?这是我正在尝试添加方法的普通类。

您正在尝试从静态方法调用非静态方法,而 Byte Buddy 在此处缺少检查。我在最新版本中添加了该检查,但您尝试执行的操作将不起作用,但这当然不会导致验证器错误。

要么method1非静态的,要么method3静态的,这将起作用。

最新更新