我有以下课
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不了解除1.8以外的-source的JDK类.
根据javac,javac仍然支持各种-source版本选项,就像以前的版本一样.
补充
我已经知道JSR 310: Date and Time 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所说.问题是该方法是在接口中定义的默认方法. 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应该更有帮助地告诉我.