Reputation: 13
I have following setting:
Class A - compiled with java 9 (class version 53)
Class B - Should be compiled with java 8 (class version 52)
Class B has a dependency to Class A.
Now I get a surprising result: I can successfully compile Class B with Java 8 although it has a dependency to the java 9 compiled class A.
If I compile Class A with Java 10 or Java 11 and then try to compile class B with Java 8 I get the expected error message:
class file has wrong version 55.0 (or 54.0), should be 52.0
So can anybody explain why I don't get the message
class file has wrong version 53.0, should be 52.0
if I try to use Java 8 with Java 9 classes?
I use this java versions:
Java 8: Oracle jdk 1.8.0_144 (installed in folder d:\jdk8)
Java 9: Oracle jdk 9.0.1 (installed in folder d:\jdk9)
Java 11: Oracle jdk 11.0.1 (installed in folder d:\jdk11)
To demonstrate it I created this two class files:
File A.java:
public class A {
public void test() {
System.out.println("Class A");
}
}
File B.java:
public class B {
public static void main(String[] args) {
A classA = new A();
classA.test();
System.out.println("Class B");
}
}
First A.java is compiled with Java 9:
d:\jdk9\bin>javac d:\test\A.java
Then B.java is compiled with Java 8 using the Class A that is compiled with Java 9:
d:\jdk8\bin>javac -cp d:\test d:\test\B.java
warning: d:\test\A.class: major version 53 is newer than 52, the highest major version supported by this compiler.
It is recommended that the compiler be upgraded.
1 warning
So the class file is compiled successfully with a warning. I just saw this warning by invoking the compiler manually. If I use Maven to build the project,
this warning wasn't visible.
Now Class A is compiled with Java 11 (same with Java 10):
d:\jdk11\bin>javac d:\test\A.java
If I try to compile Class B, I get an error:
d:\jdk8\bin>javac -cp d:\test d:\test\B.java
d:\test\B.java:3: error: cannot access A
A classA = new A();
^
bad class file: d:\test\A.class
class file has wrong version 55.0, should be 52.0
Please remove or make sure it appears in the correct subdirectory of the classpath.
1 error
So it seems that technically it's possible to use Java 9 compiled class files with Java 8. But I did not think it was possible.
Upvotes: 0
Views: 689
Reputation: 109557
The java 9 compiler javac
probably compiled for java 8; one can use a newer compiler to compile for an older .class version. Look for -target and -source 1.8.
Either the IDE or maven/gradle was configured for an older version.
Upvotes: 1