エンジニア的なネタを毎週書くブログ

東京でWebサービスの開発をしています 【英語版やってみました】http://taichiw-e.hatenablog.com/

MavenでJava9のModule(Project Jigsaw)を使ってみた

探し方が悪いのか、わざわざ書くほどのことでもないのか、mavenでJava9のmoduleを使うとどうなるか という記事が英語でも日本語でもWebで見つからなかったので、試してみました&備忘録としてブログに残しておきます。

Project Jigsaw: Quick Start Guide
こちらのQuick Startのソースを拝借しました。

f:id:taichiw:20171002230425p:plain


結論から言うと、「module-info.javaを置いておけばmoduleになる」っぽい。
(言葉の使い方が正しいのか怪しい…)

1. module使わない版

とりあえず比較用に、"Java9で導入されたmodule" ではない、ただの独立したJavaリポジトリが2つの状態。
f:id:taichiw:20171002223029p:plain

GitHub - taichiw/moduleTry at 0.1_no_module

World.java

package org.astro;

public class World {
	public static String name() {
		return "world";
	}
}

Main.java

package com.greetings;

import org.astro.World;

public class Main {
	public static void main(String[]args){
		System.out.format("Greetings %s!%n", World.name());
	}
}

com.greetings/pom.xml (一部)

<dependencies>
  <dependency>
    <groupId>groupId</groupId>
    <artifactId>org.astro</artifactId>
    <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

org.astro -> mvn install
com.greetings -> mvn package

でビルド成功。

$ java -jar com.greetings/target/com.greetings-1.0-SNAPSHOT-jar-with-dependencies.jar
Greetings world!

2. org.astro (libとして提供される側)だけmoduleにしてみる

f:id:taichiw:20171002223951p:plain

org.astro/module-info.java

module org.astro {
	exports org.astro;
}

これでも普通にビルドが通る。

3. org.astroをただのjar, com.greetingsをmoduleにしてみる

f:id:taichiw:20171002224259p:plain


何もrequiresしない場合
com.greetings/module-info.java

module com.greetings {
}

これはビルドエラー。

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project com.greetings: Compilation failure: Compilation failure:
[ERROR] ~/moduleTry/com.greetings/src/main/java/com/greetings/Main.java:[3,17] package org.astro does not exist
[ERROR] ~/moduleTry/com.greetings/src/main/java/com/greetings/Main.java:[7,54] cannot find symbol
[ERROR] symbol:   variable World
[ERROR] location: class com.greetings.Main

module-info.javaを書いた瞬間にmodule扱いになる → requiresなしでは外部パッケージが使えなくなる
ということらしい。

requiresを足してみたら
com.greetings/module-info.java

module com.greetings {
	requires org.astro;
}

org.astroというmoduleは存在しないにも関わらずビルドが通ってしまった…

IDE上では思いっきり赤線が引かれているのでなんか間違ってるかも。
f:id:taichiw:20171002225434p:plain

4. org.stroもcom.greetingsもmoduleに。

org.astroパッケージをexportする。
f:id:taichiw:20171002225642p:plain

GitHub - taichiw/moduleTry at 1.0

これはきれいにビルド成功。