Wednesday, February 17, 2010

Major Minor code of class files

Here a oneliner for finding out the bytecode version. Based on
http://en.wikipedia.org/wiki/Class_(file_format)

perl -pe 'open(FILE,$_);binmode(FILE);sysread(FILE,$buf,2,6);close(FILE);@c=unpack("H*",$buf);foreach(@c){$s.=sprintf "%s",ord($_);};$_=$s'
or
import java.io.*;

public class ClassVersionChecker {
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < args.length; i++)
            checkClassVersion(args[i]);
    }

    private static void checkClassVersion(String filename)
        throws 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();
    }
}

No comments:

Post a Comment