构建针对Java 9及更早版本的模块化Java应用程序

时间:2016-08-10 13:19:31

标签: java jigsaw

我的应用程序在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. 

我最初的想法是模块化我的应用程序并弄清楚我需要的类是否有一个公共模块来正确地声明依赖项。但是,一旦我宣布虚拟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一起使用的jar以及没有它的旧Java版本?

1 个答案:

答案 0 :(得分:4)

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

  • module-info.class编译为-source 9 -target 9,以便应用程序可以在较旧的JVM上运行,因为那些没有理由加载该类。
  • 应该使用适当的源/目标级别编译其余类(Java 9在此处不会更改任何内容)。

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

Maven pom.xml声明将应用程序可构建 runnable 保存在不同的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>
相关问题