我有以下课程.
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);
}
}
它只是编译好.
& javac ZonedDateTimeToInstant.java
它失败了-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
这是正常的吗?似乎javac
不了解-source
除了以外的JDK类1.8
.
根据javac的说法,javac
仍然-source release
像以前的版本一样支持各种选项.
补充
我已经知道JSR 310:日期和时间API仅在Java 8中可用.它有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
结论
正如@Eng.Fouad所说.问题是该方法是default method
在接口中定义的.javac
似乎抓住了这一点.
$ 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
我应该更有帮助地告诉我.
这是一个新的时间/日期API,它是在Java 8中引入的.这就是它不能用Java 7编译的原因.
toInstant()
是一种默认方法,-source 1.7
而不支持默认方法(Java 8的新功能).