0

For some reason I can't work out yet, my agent doesn't intercept java LinkageError instances.

Agent code:

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;

public class MyAgent {
    public static void premain(String arguments, Instrumentation instrumentation) {
        new AgentBuilder.Default()
            .type(ElementMatchers.isSubTypeOf(LinkageError.class))
            .transform((builder, type, classLoader, module) ->
                    builder.constructor(ElementMatchers.isDefaultConstructor())
                            .intercept(SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(MyInterceptor.class)))
            ).installOn(instrumentation);
    }
}

Interceptor code:

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

Test code:

public static void main(String[] args) {
    new NoClassDefFoundError("should be intercepted!!!").toString();
    new Foo("oh").toString();
}

What is puzzling is that replacing ElementMatchers.isSubTypeOf(LinkageError.class) with ElementMatchers.nameContains("Foo") gives the expected result and Foo constructor is intercepted.

dgt
  • 1,002
  • 8
  • 10

1 Answers1

0

The NoClassDefFoundError is loaded by the bootstrap loader. It willnot be able to see your interceptor class which is why it is never triggered.

Try using the Advice class (as a visitor) to add bytecode to matched classes which should resolve this problem.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192