javabyte-buddy

Unable to pass method to advice in byte buddy


Referencing: Problem migrating from AspectJ to Byte Buddy Plugin

When I follow the example, but update it as it should be:

package plugin;

import java.lang.reflect.Method;
import net.bytebuddy.asm.Advice;

public class TimingAdvice {
  @Advice.OnMethodEnter
  public static void onEnter(@Advice.Origin Method method)
      throws Throwable {
    System.out.println("method: " + method);
  }
}

I get: Failed to transform class SomeAdvisedClass: [java.lang.IllegalStateException: Cannot map this reference for static method or constructor start: public SomeAdvisedClass()].

For whatever reason, it works as soon as I remove the Method argument from the advice to:

package plugin;

import java.lang.reflect.Method;
import net.bytebuddy.asm.Advice;

public class TimingAdvice {
  @Advice.OnMethodEnter
  public static void onEnter(@Advice.Origin("#t") final String typeName,
  @Advice.Origin("#m") final String methodName)
      throws Throwable {
    System.out.println("type: " + typeName + ", method: " + methodName);
  }
}

I am on JDK21 with the latest version of byte buddy.

I want to pass the Method in because I want to inspect annotations on each parameter and as far as I know, I need the Method to do that.


Solution

  • It seems like you are intercepting static methods or constructors. In this case, @Advice.This cannot be assigned (in enter phase). You can define a property to rather bind null: @Advice.This(nullIfEmpty = true).