Home > Internals, Java > Knowing if a class you received is compiled for Java5 or Java6

Knowing if a class you received is compiled for Java5 or Java6


Working in a multi version environment I found my self quite often receiving a .class file compiled with the wrong compiler version. Usually receiving a .class file compiled with JDK6 whereas I was working in an environment running with JRE5.

The problem is quite simple to understand when you get it during run-time, but unfortunately you sometimes only discover it after giving the customer a hot-fix for a problem only to discover you compiled with the wrong settings. Or sometimes just to test your code you need to bounce the file between several ftp sites just to get it to the run-time environment.

So I sat a few minutes and analyzed the “header” of the binary .class file and found a simple way to know if it was compiled for Java5, or for Java6.

Open it in any HEX viewer/editor and you can see the answer:

The 8th bit (byte #7 in HEX view) is equal to 0x31 for Java5 and 0x32 for Java6.
Just a note: 0x31
=49 and 0x32=50, and 49 & 50 are the major versions for Java5 & Java6

Below you can see samples of the beginnings of two .class files:

Sample Java 5 .class file:

Sample Java 6 .class file:

It is important to mention that the above is a bit inaccurate but it is more than enough for the existing versions of Java and for the problem at hand.
The accurate definition of the .class file’s header is as such (taken from the Java 2nd edition Spec):

  • Bytes 0-3: Magic Number (Value is always – 0xCAFEBABE)
  • Bytes 4-5: Minor Version (Stored in big-endian format)
  • Bytes 6-7: Major Version (Stored in big-endian format)
    • So byte #7 (the 8th byte) is the less important byte of the 16bit unsigned integer that represents the Major Version. So when we reach Major Version 256 – the 8th byte will not be enough and I’ll have to revise this post.
Advertisements
Categories: Internals, Java Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: