Why doesn't javac compile Java 1.5 code to run on the Java 1.4 JVM?

Why can't the Java compiler compile Java 1.5 source code (for example, for each loop) into Java 1.4 bytecode?

I know that you can provide the -target 1.4 switch, which tells the compiler about the release of 1.4 compatible bytecode, but that requires -source 1.4 .

 $ javac -target 1.4 -source 1.5 Test.java javac: source release 1.5 requires target release 1.5 

Now I take a course in building the compiler, and as I understand it, compilers in any case convert the source code to an intermediate representation. Why can't such an intermediate representation be output as 1.4 compatible bytecode? This sounds like a pretty simple task, since for each cycle varargs, etc. Mostly syntactic sugar!

(Note that I see that the API classes introduced in Java 1.5 cannot explicitly be mentioned when running on the 1.4 JVM. I'm still interested in the situation when you stick with the 1.4 API.)

+4
source share
2 answers

Since Java 1.5 provides features that are simply missing from the 1.4 VM.

What should the compiler do if your source contains generics? Or the definition of enum ? What if it performs auto-update?

There are workarounds for all of these problems, but not running the Java compiler to implement workarounds. Instead, you need to either transfer your source to the Pre-Java-5 level, or use a tool like Retroweaver (there is a more modern replacement for this there, but I continue to forget its name, because, fortunately, I no longer need it use).

Also note that Java 1.5 code that does not use any new features ( enum , auto-boxing, generics) can most likely be compiled with -source 1.4 .

+4
source

You are correct that some improvements in Java 1.5 are not related to the introduction of any new changes in the style of bytecodes or class files. There are also such as annotations and listings. Therefore, an arbitrary Java 1.5 source cannot be compiled with a valid Java 1.4 class. At the same time, there is a project called retroweaver, the purpose of which is to convert Java 1.5 class files to Java 1.4 class files, available at http://retroweaver.sourceforge.net/ .

+4
source

Source: https://habr.com/ru/post/1339669/


All Articles