Java Versions

  • Thread starter Gilbert Ostlethwaite
  • Start date
G

Gilbert Ostlethwaite

Hi

Is there anyway, that given a java .class file, I can find out what
version of Java was used to compile it?

Regards
Roger
 
C

Chris Uppal

Gilbert said:
Is there anyway, that given a java .class file, I can find out what
version of Java was used to compile it?

If you really want to know which compiler, and which version of which compiler,
generated the classfile, then you will find it very very difficult -- there is
no specific information about the compiler embedded in a standard classfile.
You might be able to "fingerprint" the compilers you are interested in and
recognise the idiomatic code they generate (within the freedom allowed by the
classfile format), for instance recent versions of Sun's "javac" don't generate
jsr instructions to implement try-catch-finally blocks.

But it's more likely that you want the version of the Java platform which the
classfile was generated /for/. That's not at all the same thing since, for
instance, javac has the -target parameter, so the javac from JDK 1.6 can
generate classfiles which are marked as being suitable for running on whichever
version of the platform you choose. Anyway, it's easy to read the version
numbers from classfiles, they indicate the target platform version as follows:

major minor Java platform version required to run
45 3 1.0
45 3 1.1 // same as 1.1
46 0 1.2
47 0 1.3
48 0 1.4
49 0 1.5
50 0 1.6

Note that the default target for javac has changed over the years. IIRC in JDK
1.3 and 1.4 javac defaulted to generating classfiles only marked as requiring
at least 1.2. Later versions of javac default to requiring the same version of
the platform as their corresponding JRE.

Quick-n-dirty code for reading version numbers follows.

-- chris

===================================
import java.io.*;

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

private static void
writeVersion(String filename)
throws IOException
{
// not worth doing properly...
DataInputStream in = new DataInputStream(new
FileInputStream(filename));

if (in.read() != 0xCA
|| in.read() != 0xFE
|| in.read() != 0xBA
|| in.read() != 0xBE)
{
System.err.println(filename + "is not a valid classfile");
}
else
{
int minor = in.readShort();
int major = in.readShort();
System.out.println(filename + ": " + major + " / " + minor);
}
in.close();
}
}
===================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top