tags:

views:

2354

answers:

4

Duplicate:

Tool to read and display Java .class versions

If I have a compiled Java class, is there a way to tell from just the class file what its target version compatibility is? Specifically, I have a number of class files, compiled to Java 6, which are running under Java 5 and giving the the "Unrecognized version" error. I want to be able to look at a class file and find what its target version compatibility is without running the JVM. Any ideas?

+6  A: 

I've found this on the net and it works.

Every '.class' file starts off with the following:

  • Magic Number [4 bytes]
  • Version Information [4 bytes]

A hexdump of a '.class' file compiled with each of the following options reveals:

javac -target 1.1 ==> CA FE BA BE 00 03 00 2D
javac -target 1.2 ==> CA FE BA BE 00 00 00 2E
javac -target 1.3 ==> CA FE BA BE 00 00 00 2F
javac -target 1.4 ==> CA FE BA BE 00 00 00 30

Perhaps you could use this information to write your own '.class' file version checking utility, using Java, or perhaps a scripting or shell language ;) !

I hope this helps.

Anthony Borla

From: http://bytes.com/groups/java/16603-how-determine-java-bytecode-version

Kalecser
Great, but what about versions 1.5 and 1.6, which are the ones I care about?
Mike Pone
Seems like the last number represents the final version hex 31 = dec 49 hex 32 = dec 50. That's what I need. Thanks.
Mike Pone
Version 1.6 = 32 and 1.5 is 31
Kalecser
A: 

You can look at the byte offset 6 and 7 in the file (in a hex dump probably), which tells you which version is used. I think the Bytecode Visualizer (eclipse plugin) can see which version a class file is made for.

Further reading

Björn
+10  A: 

You can use the javap utility that comes with the standard JDK.

javap -verbose MyClass

Compiled from “MyClass.java”
public class MyClass extends java.lang.Object
SourceFile: “MyClass.java”
minor version: 3
major version: 45
bruno conde
while it may be considered "better" it is not exactly what I was looking for.
Mike Pone
+1  A: 

Taken from: http://twit88.com/blog/2008/09/22/java-check-class-version/

try {
    String filename = “C:\\MyClass.class”;
    DataInputStream in = new DataInputStream(new FileInputStream(filename));
    int magic = in.readInt();
    if (magic != 0xcafebabe) {
        log.info(filename + ” is not a valid class!”);
    }
    int minor = in.readUnsignedShort();
    int major = in.readUnsignedShort();
    log.info(filename + “: “ + major + ” . “ + minor);
    in.close();
} catch (IOException e) {
    log.info(“Exception: “ + e.getMessage(), e);
}
Kevin Crowell