2

我的应用程序在 Java 8 及更早版本上运行良好,但无法加载不属于 Java SE 的类并且失败并出现以下问题:

class MyClass (in unnamed module @0x4d14b6c2) cannot access class 
sun.tools.attach.HotSpotVirtualMachine (in module jdk.attach) because 
module jdk.attach does not export sun.tools.attach to unnamed module 
@0x4d14b6c2. 

我最初的想法是模块化我的应用程序并确定我需要的类是否有一个公共模块来正确声明依赖关系。但是,一旦我宣布 dummy module-info.javajavac就开始抱怨:

modules are not supported in -source 1.6; use -source 9 or higher to enable modules

编辑:我正在指示 maven-compiler-plugin 生成与 java 6 兼容的字节码,因为我需要应用程序来支持它。实际使用的参数是-g -nowarn -target 1.6 -source 1.6 -encoding UTF-8.

也许我遗漏了一些明显的东西,但是我如何构建一个可以与 Jigsaw 以及没有它的旧 Java 版本一起使用的 jar?

4

1 回答 1

4

在 Jigsaw 开发邮件列表的帮助下,我设法构建了模块化代码库。(我最终不需要HotSpotVirtualMachine特别)。

  • 编译module-info.class-source 9 -target 9使应用程序可在较旧的 JVM 上运行,因为这些 JVM 没有理由加载该类。
  • 其余的类应该用适当的源/目标级别编译(Java 9 在这里没有改变任何东西)。

因此需要两次javac调用:默认情况下只编译类并跳过模块描述符,如果使用 Java 9 编译,则编译模块描述符会跳过所有常规类。


Maven pom.xml 声明以保持应用程序在不同 JDK 版本之间可构建可运行有点笨拙但有效:

    <!--
        When using compiler from java 8 and older, ignore module files altogether.
        Otherwise, use 2 phase compilation to build
          - all classes for target version and
          - module-info.java with 9+ source and target level
     -->
    <profiles>
      <profile>
      <id>jigsaw</id>
      <activation>
        <jdk>[1.9,)</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
              <source>1.9</source>
              <target>1.9</target>
            </configuration>
            <executions>
              <execution>
                <id>module-infos</id>
                <phase>compile</phase>
                <goals>
                  <goal>compile</goal>
                </goals>
                <configuration>
                  <includes>
                    <include>**/module-info.java</include>
                  </includes>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
        <executions>
          <execution>
            <id>default-compile</id>
            <configuration>
              <excludes>
                <exclude>**/module-info.java</exclude>
              </excludes>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
于 2016-08-29T05:19:10.570 回答