2017-07-20 236 views
0

由于某些原因,我还无法解决,我的代理程序不拦截java LinkageError实例。用bytebuddy拦截错误构造函数

代理代码:

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); 
    } 
} 

拦截代码:

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

测试代码:

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

更令人不解的是,随着ElementMatchers.nameContains("Foo")更换ElementMatchers.isSubTypeOf(LinkageError.class)给出了预期的结果和Foo构造被拦截。

+0

bytebuddy版本 - 1.7.1 – dgt

回答

0

NoClassDefFoundError由引导加载程序加载。它将无法看到你的拦截器类,这是它永远不会被触发的原因。

尝试使用Advice类(作为访问者)将字节码添加到可以解决此问题的匹配类中。