Thursday, February 21, 2008

How to find java class version?

The first 4 bytes are a magic number, 0xCAFEBABe, to identify a valid class file then the next 2 bytes identify the class format version (major and minor).
Possible major/minor value :
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

import java.io.*;

public class ClassVersionChecker {
static void main(String[] args) throws IOException {
(int i = 0; i < args.length; i++)   
checkClassVersion(args[i]); }
private static void checkClassVersion(String filename)
IOException  { 
DataInputStream in =
new DataInputStream (new FileInputStream(filename));
int magic = in.readInt(); 
if(magic != 0xcafebabe)
{
System.out.println(filename + " is not a valid class!");;
 }
int minor = in.readUnsignedShort();
 int major = in.readUnsignedShort();
 System.out.println(filename + ": "
 + major + " . " + minor);
 in.close();
 } }

> java ClassVersionChecker ClassVersionChecker.class
ClassVersionChecker.class: 49 . 0