During the development of the Java generics specification (and other language features added in Java 5), experimental support was added to the
javac compiler to allow it to consume Java 5 language features and generate bytecode that could be run on a Java 1.4 JVM. While these features are not supported (or even documented), they are used by a number of open source projects to allow developers to code using Java 5 language features and produce JAR files that can be used on earlier JVMs. And, now that
javac is open source, it is possible the features might be supported by a third party. To activate these features, you can invoke
javac with the
-source 1.5 and
-target jsr14 options.
The JSR 14 target mode of
javac causes the compiler to emit JDK 1.4-compatible bytecode corresponding to Java 5 language features:
- Generics and varargs: The casts inserted by the compiler in the presence of generics have no dependency on the class library, and so they can execute equally well on a pre-5 JVM. Similarly, the code generated by the compiler in the presence of variable-length argument lists has no dependency on the class library.
for-eachloop: When iterating over an array, the compiler generates an induction variable and the standard array iteration idiom. When iterating over a
Collection, the compiler generates the standard iterator-based idiom. When iterating over a non-Collection
Iterable, the compiler produces an error.
- Autoboxing: Rather than generating calls to the
valueOf()method in the wrapper class, the compiler generates calls to the constructor instead.
- String concatenation: The JSR 14 target mode of
javaccauses the compiler to generate calls to
- Enumerations: The JSR 14 target mode of
javachas no special support for enumerations. Code that attempts to use enumerations will fail with a
NoClassDefFoundErrorlooking for the
Using the JSR 14 target mode allows you to write code that uses generics, autoboxing, and the for-each loop in the “easy” cases, which may suffice for many projects. It is convenient, if unsupported, and the compiler generates mostly compatible bytecode in a single pass.