Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java API to find out the JDK version a class file is compiled for?

Tags:

java

version

Are there any Java APIs to find out the JDK version a class file is compiled for? Of course there is the javap tool to find out the major version as mentioned in here. However I want to do it programmatically so that that I could warn the user to compile it for the appropriate JDK

like image 789
Prabhu R Avatar asked Aug 18 '09 11:08

Prabhu R


People also ask

How can I tell what version of Java a compiled class is?

In Java, we can use javap -verbose className to print out the class information. D:\projects>javap -verbose Test Classfile /D:/projects/Test. class Last modified 16 Apr 2019; size 413 bytes MD5 checksum 8679313dc0728e291898ad34656241cb Compiled from "Test.

Are Java class files compiled?

A Java class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine.

What is Javap command in Java?

DESCRIPTION. The javap command disassembles one or more class files. Its output depends on the options used. If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it. javap prints its output to stdout.


2 Answers

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 possible values are :

major  minor Java platform version  45       3           1.0 45       3           1.1 46       0           1.2 47       0           1.3 48       0           1.4 49       0           5 50       0           6 51       0           7 52       0           8 53       0           9 54       0           10 55       0           11 56       0           12 57       0           13 58       0           14 
like image 144
RealHowTo Avatar answered Sep 23 '22 03:09

RealHowTo


basszero's approach can be done via the UNIX command line, and the "od(1)" command:

% od -x HelloWorldJava.class |head -2 0000000 feca beba 0000 3100 dc00 0007 0102 2a00 0000020 6f63 2f6d 6e65 6564 6163 642f 6d65 2f6f 

"feca beba" is the magic number. The "0000 3100" is 0x31, which represents J2SE 5.0.

like image 42
rickumali Avatar answered Sep 22 '22 03:09

rickumali