Wednesday, 23rd June 2010
The new frontier for learning Java

Check the class version

From WikiJava

Jump to: navigation, search


This tutorial will show how to get the version number of a compiled .class file

Contents

the article

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 :

ClassVersionChecker.java

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();
    }
}

the output

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

See Also

The Java Virtual Machine Specification, Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Title (required):

Website:

Comment: