4

我一直在使用 Java Attach API(tools.jar 的一部分)附加到正在运行的 java 进程,并从内部将其关闭。

它在 Windows 上完美运行。但是,当在 linux 上运行时尝试实际执行附加代码时,我得到一个java.lang.NoClassDefFoundError带有以下堆栈跟踪的原因...

java.lang.ClassNotFoundException:com.sun.tools.attach.VirtualMachine...
    java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    java.security.AccessController.doPrivileged(Native Method)
    java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    java.lang.ClassLoader.loadClass(ClassLoader.java:247)

我正在使用 Maven,到目前为止我有这个部分,以便包含 tools.jar。

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.4.2</version>
    <scope>system</scope>
    <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>

值得注意的是 ${java.home} 评估为 jre,但即使我将其更改为 jdk 的直接路径,问题也是一样的。

我好难过...

4

1 回答 1

5

原来这是 maven 构建的问题。系统范围要求容器在启动时在类路径上传递 tools.jar。一个简单java -jar的不这样做(我不想添加显式的类路径参数)。

我为解决这个问题而提出的解决方案是让 maven 构建使用配置文件选择位置,然后在打包阶段之前将 jar 预安装在本地 repo 中(允许依赖只是正常的依赖)。

配置文件部分...

<profiles>
    <profile>
        <id>default-profile</id>
        <activation>
            <activeByDefault>true</activeByDefault>
            <file>
                <exists>${java.home}/../lib/tools.jar</exists>
            </file>
        </activation>
        <properties>
            <toolsjar>${java.home}/../lib/tools.jar</toolsjar>
        </properties>
    </profile>
    <profile>
        <id>osx_profile</id>
        <activation>
            <activeByDefault>false</activeByDefault>
            <os>
                <family>mac</family>
            </os>
        </activation>
        <properties>
            <toolsjar>${java.home}/../Classes/classes.jar</toolsjar>
        </properties>
    </profile>
</profiles> 

安装文件部分...

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <executions>
        <execution>
            <id>jdk_tools</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>install-file</goal>
            </goals>
            <configuration>
                <groupId>com.sun</groupId>
                <artifactId>tools</artifactId>
                <version>1.4.2</version>
                <packaging>jar</packaging>
                <file>${toolsjar}</file>
            </configuration>
        </execution>
    </executions>
</plugin>

依赖性

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.4.2</version>
</dependency>
于 2013-05-08T16:59:18.967 回答