将代理附加到类路径

Append Agent to classpath

我正在尝试使用 byte buddy 检测 Java ThreadPoolExecutor class。我正在使用自己的记录器从代理获取日志。但是当我尝试将此记录器与 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 对此 的回答,我在代理中使用以下代码将我的代理 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

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

似乎您正在将相同的 class 添加到多个 class 加载器,这可能会导致问题,尤其是如果您懒惰地添加那些 class。理想情况下,您可以使用 Maven 的 Shade 插件或 Gradle 的 Shadow 插件等构建工具将所有 classes 捆绑到代表 Java 代理的 jar 文件中。