为什么在Linux上使用Java Attach API会失败?(即使maven构建完成)

Tom*_*Tom 4 java exception maven tools.jar

我一直在使用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)
Run Code Online (Sandbox Code Playgroud)

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

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

我很难过......

Tom*_*Tom 5

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

我解决这个问题的解决方案是让maven构建使用配置文件选择位置,然后在包阶段之前在本地存储库中预先安装jar(允许依赖性只是正常的依赖性).

简介部分......

<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> 
Run Code Online (Sandbox Code Playgroud)

安装文件部分......

<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>
Run Code Online (Sandbox Code Playgroud)

扶养

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.4.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)