Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't javac compile Java 1.5 code to run on Java 1.4 JVMs?

Tags:

java

javac

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.)

like image 800
aioobe Avatar asked Feb 26 '23 02:02

aioobe


2 Answers

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 enum definition? 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.

like image 195
Joachim Sauer Avatar answered Mar 07 '23 03:03

Joachim Sauer


You are correct that some enhancements in Java 1.5 did not involve the introduction of any new bytecodes or class file format changes. There are others like annotations and enums that did. Therefore arbitrary Java 1.5 source cannot be compiled to a valid Java 1.4 class. That being said there is a project named retroweaver that aims to transform Java 1.5 class files to Java 1.4 class files available at http://retroweaver.sourceforge.net/.

like image 32
Geoff Reedy Avatar answered Mar 07 '23 04:03

Geoff Reedy