Write Java with JDK 1.5 features and run on JRE 1.4

JavaHave you being writing your Java code on Java 1.5 (JDK 1.5) with new features like auto boxing, generics and enums? And suddenly realized that your customer's servers are still using Java 1.4 (JRE 1.4)? This is not a surprise since most of the customers are not in a position to take a risk and try the newer versions as they are running live/online businesses. But as professionals in the software development field, we have to move with the latest/stable versions available in the market. That's where the conflict occurs.

Now you must deploy your Java 1.5 codes into a 1.4 Java runtime environment (even may be 1.3 or 1.2). Even if the Java code has not used any of the new features of Java 1.5, you still can not run your code in 1.4 JRE as the runtime throws an error saying "java.lang.UnsupportedClassVersionError".

Compile 1.5 codes for 1.4 JVM

Java compiler provides an option to specify the target JVM of the generated classes like 1.5, 1.4, and 1.3 as follows.

public class MyClass {
public static void main(String args[]) {
System.out.println("Main Method");
}
}

> javac -source 1.4 -target 1.4 MyClass.java

Even if your JDK is of version 1.5, above command will compile your class so that it can run on a JRE 1.4. But the above option only works if your class does not use any of the new features in Java 1.5 (like auto boxing, enums etc).

Check the following class. Compiling it with "target" option will result in a compile time error.

public class MyClass {
public static void main(String args[]) {
Integer count = 1;
System.out.println("Main Method");
}
}

> javac -source 1.4 -target 1.4 MyClass.java

The compiler error is shown because auto boxing is not supported in 1.4.

This means that we can not use 1.5 features if we are going to run the programs on an older version. So this is not a real solution for our issue.

Can not run/deploy code with new features on 1.4 JVM?

Java retroweaver logoThere is an open source free solution to this issue. The tool is named "Retroweaver", and it can generate class files for older JREs using classes with new features of the 1.5 version. This is a nice tool and it supports most of the Java 1.5 features.

Retroweaver site says;

... supports most 1.5 features while running on 1.4.
  • generics
  • extended for loops
  • static imports
  • autoboxing/unboxing
  • varargs
  • enumerations
  • annotations

Also this has a good documentation (even though it's not up to date. Don't blame them; they are doing it for free).

This tool can convert .class files of 1.5 version to another older JRE version. Also it has the capability of converting a complete .jar file.

Check out this stream