tags:

views:

2920

answers:

5

Do any of you know of a tool that will search for .class files and then display their compiled versions?

I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).

+1  A: 

I recommend: DJ Java Decompiler. It's free to try and costs $19.99 to purchase.

I've also heard good things about Cavaj, but never used it personally. It's freeware, so definitely worth a try.

As far as searching for the files, I have it integrated with my eclipse setup. With my configuration, when I click on a .java file it opens in eclipse and when I click on a .class file, it opens in DJ Java Decompiler.

Ryan Guest
+1  A: 

You could load them with the BCEL.

JavaClass javaClass = Repository.lookupClass("foo.Bar");
System.out.println(javaClass.getMajor() + "." + javaClass.getMinor());

The class JavaClass has getMajor() and getMinor() methods for inspecting the class version.

That said, it is easy enough to read the class file signature and get these values without a 3rd party API. All you need to do is read the first 8 bytes.

ClassFile {
    u4 magic;
    u2 minor_version;
    u2 major_version;

For class file version 50.0 (Java 1.6), the opening bytes are:

CA FE BA BE 00 00 00 32

...where 0xCAFEBABE are the magic bytes, 0x0000 is the minor version and 0x0032 is the major version.

public class Demo {

    private static int toInt(byte upper, byte lower) {
        int ret =  upper << 8;
        ret |= lower;
        return ret;
    }

    public static void main(String[] args) throws Exception {
        ClassLoader loader = Demo.class.getClassLoader();
        InputStream in = loader.getResourceAsStream("Demo.class");
        try {
            byte[] buffer = new byte[8];
            in.read(buffer);
            //TODO: error checking
            int minor = toInt(buffer[4], buffer[5]);
            int major = toInt(buffer[6], buffer[7]);
            System.out.println(major+"."+minor);
        } finally {
            in.close();
        }
    }
}

Walking directories (File) and archives (JarFile) looking for class files is trivial.

McDowell
+7  A: 

Use the javap tool that comes with the JDK. The -verbose option will print the version number of the class file.

> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
  SourceFile: "MyClass.java"
  minor version: 0
  major version: 46
...
staffan
+1  A: 

If you are on a unix system you could just do a

find /target-folder -name \*.class | xargs file | grep "version 50\.0"

(my version of file says "compiled Java class data, version 50.0" for java6 classes).

WMR
+2  A: 

Have a look at:

http://code.google.com/p/versioncheck/