LoginSignup
6
6

More than 3 years have passed since last update.

MavenのデフォルトJDKのバージョンは1.5

Last updated at Posted at 2019-11-09

はじめに

Javaで個人的に遊んでいたところ、ちょっとはまったことがあった。
割と基本的なことなのかもしれないけど、知らかなったので備忘録的に記載しておく。
(資格で得た知識が多いからこういう実践的なところが結構抜けてるんだよなぁ・・・)

発生した事象

Maven の project update を実行すると、JDK 1.5 でコンパイルされるため、JDK 1.6 以降の構文で記載したプログラムはコンパイルエラーになる。

以下、詳細。

事前の状態。
JRE System Library が 1.8 に設定されている。
image.png

右クリック⇒Maven⇒Update Project を実行
(またはAlt+F5)
image.png

JRE System Library が 1.5 に変更されてしまう。
image.png

1.5 なので、1.7 から導入された try-with-resources はコンパイルエラー
image.png

ダイヤモンド演算子が導入されたのも1.7からなので、コンパイルエラー
(右辺にも型を明示するかJRE 1.7にしろと言われている)
image.png

調べてみた

以下のサイトを見たところ、Mavenプロジェクトのデフォルトのコンパイラバージョンが1.5になっていることが原因らしい。

MavenでJDKのバージョンを指定する方法【JDK1.5 -> 1.8】
Maven:コンパイラのバージョン設定
Setting the -source and -target of the Java Compiler

対応策

Apache Mavenのサイトに書いてあることを参考に、pom.xmlを修正。
こうすることでJREのバージョンを指定することができる。
やり方は以下の①と②があるけど、今回は①を実施。

①project properties にて source と target に 1.8 を指定

今回は1.8を指定。

pom.xml
  <properties>
    ・・・
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    ・・・
  </properties>

② plugin directly で source と target に 1.8 を指定

今回はこっちの書き方をしていないが、これでも行けるらしい。

pom.xml
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

対策後に確認

上記①(又は②)の修正をした後、再度、右クリック⇒Maven⇒Update Project を実行
(またはAlt+F5)
⇒JRE System Library が 1.8になる。

image.png

try-with-resourcesのコンパイルエラーが解消されていることを確認。
image.png

ダイヤモンド演算子のコンパイルエラーも解消。
image.png

以上。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6