I have a question about the compliance mode.
What happens with my class which extends a basic java class, for example Properties and is compiled with JDK5 and packaged into a jar. Now I use this jar in a project which gets build with JDK 6 but in compliance mode 5.
Can someone now use the new method stringPropertyNames() – which is new in JDK6 – on my class in the JDK6 project?
I have a question about the compliance mode. What happens with my class which
Share
It works, as long as you run your project on JRE 6 JVM. And you don’t need your project to be compiled with compliance to Java 1.5. That is, when compiling your project, you don’t need to use either
-source 1.5nor-target 1.5options.On the other hand, when running you project on JRE 5 JVM, it will fail with
regardless of the options used on compilation of your project.
What happens in runtime, is that the JVM searches corresponding execution bytecode for
Properties.stringPropertyNames(). When running on JRE 6, such code exists (no matter what options were used in compilation). When running on JRE 5, it doesn’t exist.I checked the scenario you suggested:
B.java:
C.java:
The following output resulted the same, compiling with JDK 6, either using
-source 1.5and/or-target 1.5or not.Output on JVM 6:
Output on JVM 5:
So, why use
-sourceand-targeton compilation at all?This site explains succinctly that you can use
-sourceoptions to make the compiler fail if certain features of releases later than the specified are used. E.g.,-source 1.4ensures you don’t use generics (which would otherwise fail only at runtime).The
-targetoptions is, according to the official docs, for enabling executing the compiled code on other (earlier) JVMs. E.g, if I use JDK 6 to compile my code but I need it to run on JVM 5, I’d use-target 5on compilation. If I don’t, I’ll getjava.lang.UnsupportedClassVersionError: Bad version number in .class file.I hope you’re not overwhelmed by the answer ;)…