Search code examples
javajava-7portingjava-6

Compiling Java 7 to Java 6


I'm aware that the runtime features of Java 7 are not available with Java 6 but since no new byte code has been added the new byte code invokedynamic is only relevant for non-Java languages, I was wondering how hard it would be to convert Java 7 source code (new switch statement, diamond operator) to pure Java 6 (i.e. to be able to start to convert the source to Java 7 without losing Java 6 compatibility).

Any pointers?


Solution

  • Mark a .class file output by Java 7 javac with version 1.6.0 (i.e. 0x32)

    printf "\x00\x00\x00\x32" |dd of=Example.class seek=4 bs=1 count=4 conv=notrunc
    

    (according to http://en.wikipedia.org/wiki/Java_class_file#General_layout)

    If you put that (using $1 for the filename) into j6patch you can do all class files with:

    find . -name \*.class |xargs -I {} ./j6patch {}
    

    I used this on a large (~4.8 MB jar) code base and even used RetroTranslator on the java 6 jar so Java 7 language features can be used on an app that runs in Java 5. Also the Java 7 compiler (javac) does lots of extra optimizations (e.g. escape analysis) that very noticeably improves performance.

    Using RetroTranslator with -verify -target 1.5 and JRE 1.6 runtime jars allows to verify that no Java 7 runtime features are used.