byte-buddy Advice 或 Intercept Constructor 调用

问题描述

我试图拦截或建议构造函数调用如下:

new AgentBuilder.Default()
            //.disableClassFormatChanges()
            .with(AgentBuilder.RedeFinitionStrategy.RETRANSFORMATION)
            .with(AgentBuilder.Typestrategy.Default.redefine)
            .type(ElementMatchers.nameMatches("org.openqa.selenium.firefox.FirefoxDriver"))
            .transform((builder,typeDescription,classLoader,module) -> builder
                   .constructor(ElementMatchers.any())
                   .intercept(SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(FirefoxDriverInterceptor.class))))
                   //.intercept(SuperMethodCall.INSTANCE.andThen(Advice.to(FirefoxDriverConstructorAdvice.class))))

拦截器:

@RuntimeType
public static void intercept(@Origin Constructor<?> constructor) {
    System.out.println("Intercepted: " + constructor.getName());
}

建议:

@Advice.OnMethodExit
public static void after(//@Advice.This Object thisObject,@Advice.Origin String method,@Advice.AllArguments Object[] args
) {
    logger.info("<----- instantiated firefoxwebdriver: {}",method);
}

尝试使用拦截器或建议时,抛出异常是:

java.lang.IllegalStateException: Cannot call super (or default) method for public org.openqa.selenium.firefox.FirefoxDriver(org.openqa.selenium.firefox.GeckoDriverService,org.openqa.selenium.Capabilities)
at net.bytebuddy.implementation.SuperMethodCall$Appender.apply(SuperMethodCall.java:102)
at net.bytebuddy.implementation.bytecode.ByteCodeAppender$Compound.apply(ByteCodeAppender.java:134)

让我知道错误的指针。感谢您的帮助。

解决方法

您在此处混合了不相关的 AdviceMethodDelegation。它们有一些共同的概念,但不能混用注释。

然而,您可以将建议包装在委托中:

Advice.to(...).wrap(MethodDelegation.to(...))