Java program to check compiler version information of a class

Hi All,

Below is the java program which print the compiler version information where the classes being compiled. To get a complete details of class structure.
Please read the article https://rocksolutions.wordpress.com/2010/06/20/way-to-check-the-java-class-file-is-compiled-into-which-version/

package com.test.unit;

import java.io.*;
/*
@Author R Vashi
*/
public class ClassVersionChecker {
public static void main(String[] args) throws Exception {

/*
* Possible major/minor value :
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                  1.5
50               0                  1.6

*
* To riun this API first of extract all the classes into one location. This version doent read the classes inside Jar/zip file.
*/
getCompilerVersionInfoForClassesInDir(“c:\\documents and settings\\myApp\classes”);
}

private static void getCompilerVersionInfoForClassesInDir(String dir)
throws Exception {
if (dir == null) {
throw new Exception(
“Directory Name is null, Please check and try again”);
}
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println(“No directory provided”);
return;
}
iterateFiles(directory);

}

private static void iterateFiles(File directory) throws Exception {
File[] files = directory.listFiles();
for (File f : files) {
if (f.isDirectory()) {
iterateFiles(f);
} else {
checkClassVersion(f.getAbsolutePath());
}
}
}

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 + “\t\t\t\t: ” + major + ” . ” + minor);
in.close();
}
}

Thanks
R Vashi

Advertisements

One thought on “Java program to check compiler version information of a class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s