将代理附加到类路径

时间:2018-04-19 13:03:42

标签: javaagents byte-buddy

我正在尝试使用byte buddy来设法Java ThreadPoolExecutor类。我正在使用自己的记录器从代理获取日志。但是当我尝试将此记录器与Advice一起使用时,会出现以下错误。

Exception in thread "main" java.lang.NoClassDefFoundError: com/github/shehanperera/threadagent/GetLoggers
        at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.<clinit>(ThreadPoolExecutor.java)
        at java.util.concurrent.ThreadPoolExecutor.<clinit>(ThreadPoolExecutor.java:550)
        at java.util.concurrent.Executors.newFixedThreadPool(Executors.java:89)
        at com.github.shehanperera.threadpool.RunThreads.main(RunThreads.java:23)

使用Rafael Winterhalter对此Slf4j loggers with Byte Buddy的回答,我在代理中使用以下代码将我的代理jar加载到引导路径。

JarFile jarFile = null;
        try {
            jarFile = new JarFile(new File("threadpool-agent-1.0-SNAPSHOT.jar"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        instrumentation.appendToBootstrapClassLoaderSearch(jarFile); 

但现在我收到了以下错误

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
        at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.LinkageError: loader constraint violation: when resolving method "net.bytebuddy.agent.builder.AgentBuilder$Default.ignore(Lnet/bytebuddy/matcher/ElementMatcher;)Lnet/bytebuddy/agent/builder/AgentBuilder$Ignored;" the class loader (instance of sun/misc/Launcher$AppClassLoader) of the current class, com/github/shehanperera/threadagent/Agent, and the class loader (instance of <bootloader>) for the method's defining class, net/bytebuddy/agent/builder/AgentBuilder$Default, have different Class objects for the type net/bytebuddy/matcher/ElementMatcher used in the signature
        at com.github.shehanperera.threadagent.Agent.premain(Agent.java:33)
        ... 6 more

有什么建议可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

好像你将同一个类添加到多个类加载器会导致问题,特别是如果你懒得添加这些类。理想情况下,您使用构建工具(如Maven的Shade插件或Gradle的Shadow插件)将所有类捆绑到代表Java代理的jar文件中。