Eclipse:A JNI error has occured, please check your installation and try again

問題

Eclipseで突然以下のエラーが発生するようになった。

Error: A JNI error has occured, please check your installation and try again.

コンソールには以下が表示される。

java.lang.UnsupportedClassVersionError: .... has been compiled by a more recent version of the Java Runtime (class file version 54.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)

メッセージの意味

最初のダイアログで「JNI error」と言っているが、これはJNIとは、ほぼ関係無い。「上位バージョンのJavaでコンパイルされた.classファイルを上位バージョンで実行しようとしている」という意味だ。

具体的には、この場合54.0というのはJava10でコンパイルされた.classを表し、「52.0までしかサポートしてない」というのはJava8のことである。これについてはJavaバージョンの下の方に記述がある。

つまり、「コンパイルはJava10で行いながら、実行はJava8で行おうとしている」ということで、それはできないわけだ。

原因

これがEclipseで発生したわけだが、原因の経緯としてはこうだ。

  • マシンにはJava10、Java8をインストールしており、デフォルトはJava10にしている。
  • Eclipseも当然Java10上で動作させ、デフォルトの開発対象はJava10である。
  • しかし、このプロジェクトはJava8上での動作にしたかったので、「プロジェクト設定」としてターゲットをJava8に指定した。

以下のように、プロジェクト独自の設定としてJava8を指定している。

そして、Run ConfigurationとしてもJava8を指定している。

ところがある時、.settingsフォルダを削除した。実はこの中に「プロジェクト独自の設定ファイル」であるorg.eclipse.jdt.core.prefsファイルが格納されている。以下のようなものだ。

org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error

これを削除してEclipseを再起動し、プロジェクトのプロパティを見てみると、以下になっている。

つまり、プロジェクト独自の設定(Java8)は消え、Eclipse全体の設定(Java10)が適用されてしまっている。この状態でもRun Configurationは相変わらずJava8になっている。

その結果、「コンパイルはJava10で、実行はJava8で」という状態になってしまったわけだ。

本来の意図

本来の意図としては、.settings以下のgit管理をやめるために削除したのだが、gradleのeclipseプラグインでの再生成を忘れていた。

このプラグインでは、.classpath, .project, .settings/org.eclipse.jdt.core.prefsファイルを自動作成してくれる。