Why can’t the Java compiler compile Java 1.5 source code (with for-each loops for instance) to Java 1.4 bytecode?
I know that you can provide a -target 1.4 switch, which tells the compiler to produce 1.4 compliant bytecode, but this requires -source 1.4 as well.
$ javac -target 1.4 -source 1.5 Test.java
javac: source release 1.5 requires target release 1.5
I’m taking a course in compiler construction now, and as I understand it, compilers transform the source code into an intermediate representation anyway. Why can’t such intermediate representation be output as 1.4 compliant bytecode? It sounds like an easy enough task, since, for each loops, varargs etc are basically just syntactic sugar!
(Note that I can see that API classes introduced in Java 1.5 obviously can’t be referred to when executing on a 1.4 JVM. I’m still interested in the situation in which you stick to the 1.4 API.)
Because Java 1.5 provides features that are simply not present in a 1.4 VM.
What should the compiler do if your source contains generics? Or an
enumdefinition? What if it does autoboxing?There are workarounds for all of these issues, but it’s not the job of the Java compiler to implement workarounds. Instead you either need to port your source to a Pre-Java-5 level or use a tool such as Retroweaver (there’s a more modern replacement for that out there, but I keep forgetting its name, since luckily I no longer need to use it).
Also note that Java 1.5 code that doesn’t use any of the new features (
enum, auto-boxing, generics) most likely can be compiled using-source 1.4.