Tuesday, July 12, 2011

Bad Version Number in .class file

java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12

If you have been developing in java and have been at it for a while..you may have encountered the above exception...

Before jumping into the fix, lets first discuss the problem itself..."Bad Version number in .class file"...What does it mean?

To figure it out, run the command javap -verbose {classFileName} on the command prompt(assuming win os). Sometimes the output generated is too much, so you might want to direct the output to a file.
Now in the output of the above command, search for words such as major version and minor version and you will find something like (obviously, the numbers can be different in your case)

  minor version: 0
  major version: 50


The following table tells you that the java platform version for the combination is 1.6
major  minor Java platform version 
45       3           1.0
45       3           1.1
46       0           1.2
47       0           1.3
48       0           1.4
49       0           1.5
50       0           1.6
 
Essentially, this means that my code was compiled using java 1.6. Now your error happens when the java runtime tries to run the file and finds the version number in the .class file inappropriate. This can only happen if your runtime java version is lower than the compile time java version.

The fix: Fix the runtime java version or compile in a lower version of java as appropriate. In an ideal world, both of them should be the same but they may differ for a variety of reasons,so just make sure the runtime version is the same or higher than the compile time version...

Now, depending on how you are running your program..you will need to make changes at different places...if you were running your program in Eclipse..you will need to change the 'Run' configuration (JRE tab)..if you are dropping a library in ant by developing a custom task..you will need to make sure that ant has a suitable version of java..(to figure out which version of java ant is using..run ant in the verbose mode)..pointing  JAVA_HOME to the correct jdk/jre typically fixes the ant issue

Hope this helps..