Its easy to get the details of the JRE version using System.getProperties(). A more difficult task was to find out the version of the class file. I could not find any API which did it :(. But I did find out that these details were available in the class file, so I wrote a small code to determine if the class will run on the current version of JRE.
import java.io.DataInputStream;
import java.io.FileInputStream;
public class ClassRuntimeVersion {
public static void main(String[] args) throws Exception {
FileInputStream fis = null;
DataInputStream dis = null;
try {
if (args.length != 1) {
throw new Exception("specify the class file");
}
fis = new FileInputStream(args[0]);
dis = new DataInputStream(fis);
if (dis.readInt() != 0xCAFEBABE) {
throw new Exception("not a class file");
}
short minorVersion = dis.readShort();
short majorVersion = dis.readShort();
System.out.println("Java Class version info");
System.out.println("1.6 50");
System.out.println("1.5 49");
System.out.println("1.4 48");
System.out.println("1.3 47");
System.out.println("-------------------------");
float classVersion = Float.parseFloat(majorVersion + "."
+ minorVersion);
System.out.println("Class file compiled version : " + classVersion);
float jreJavaVersion = Float.parseFloat(System
.getProperty("java.class.version"));
System.out.println("JRE version : " + jreJavaVersion);
if (jreJavaVersion < classVersion) {
System.err.println("You r dead dude, versions did not match");
}
} finally {
if (fis != null) {
fis.close();
}
if (dis != null) {
dis.close();
}
}
}
}
No comments:
Post a Comment