Java – jdk8 with – source 1.7 [default method]
I have the following classes
public class zoneddatetimeToInstant {
public static void main(final String[] args)
throws NoSuchMethodException {
assert Chronozoneddatetime.class.isAssignableFrom(zoneddatetime.class);
final Method toInstant
= Chronozoneddatetime.class.getmethod("toInstant");
final zoneddatetime Now = zoneddatetime.Now();
final Instant instant = Now.toInstant();
System.out.println(instant);
}
}
It just compiles fine
& javac zoneddatetimeToInstant.java
And it failed with - source 1.7
& javac -source 1.7 zoneddatetimeToInstant.java
zoneddatetimeToInstant.java:10: error: cannot find symbol
final Instant instant = Now.toInstant();
^
symbol: method toInstant()
location: variable Now of type zoneddatetime
1 error
1 warning
Is this normal? It seems that javac can't remove the JDK class of - source other than 1.8
According to javac, javac still supports various - source version options, just like previous versions
supplement
I already know that the JSR 310: date and time API is only available in Java 8 What does it have to do with javac?
$cat Java8.java
public class Java8 {
public void print(java.io.PrintStream out) {
out.printf("hello world\n");
}
}
$javac Java8.java
$cat Java7.java
public class Java7 {
public static void main(final String[] args) {
new Java8().print(System.out);
}
}
$javac -source 1.7 -target 1.7 Java7.java
warning: [options] bootstrap class path not set in conjunction with -source 1.7
1 warning
$java Java7
hello world
conclusion
As @ Eng. Fouad said The problem is that this method is the default method defined in the interface Javac seems to grasp this point
$cat Java8i.java
public interface Java8i {
default void print(java.io.PrintStream out) {
out.printf("hello world\n");
}
}
$javac Java8i.java
$cat Java8c.java
public class Java8c implements Java8i {
}
$javac Java8c.java
$cat Java7i.java
public class Java7i {
public static void main(final String[] args) {
new Java8c().print(System.out);
}
}
$javac -source 1.7 -target 1.7 Java7i.java
warning: [options] bootstrap class path not set in conjunction with -source 1.7
Java7i.java:3: error: cannot find symbol
new Java8c().print(System.out);
^
symbol: method print(PrintStream)
location: class Java8c
1 error
1 warning
Javac should tell me more helpfully
Solution
This is a new time / date API introduced in Java 8 This is why it cannot be compiled in Java 7
Toinstant() is a default method, while - source 1.7 does not support the default method (a new feature of Java 8)
