How to programmatically determine the Java byte code version of the current class?

I have a situation where the deployment platform is Java 5, and development takes place with Eclipse for Java 6, where we set up the procedure for creating a new workspace when starting work on this project. Therefore, one of the necessary steps sets the compiler level in Java 5, which is often forgotten.

We have a test machine with a deployment platform where we can run the code that we create and perform initial testing on our computers, but if we forget to switch the compiler level, the program will not work. We have a build server to create what goes to the client, which works well, but this is for development, where the build server is not needed and will add unnecessary expectations.

Question: CAN programmatically determine the version of the byte code of the current class, so my code can print a warning already during testing on my local PC?


EDIT: Note that this requirement is for the current class. Is this accessible through class class? Or should I find the class file for the current class, and then examine this?

+3
source share
5 answers

Easy way to find this to run javap in class

... http://download.oracle.com/javase/1,5.0/docs/tooldocs/windows/javap.html

:

M:\Projects\Project-1\ant\javap -classpath M:\Projects\Project-1\build\WEB-INF\classes -verbose com.company.action.BaseAction

minor version: 0
major version: 50
+7

resource .

//TODO: error handling, stream closing, etc.
InputStream in = getClass().getClassLoader().getResourceAsStream(
    getClass().getName().replace('.', '/') + ".class");
DataInputStream data = new DataInputStream(in);
int magic = data.readInt();
if (magic != 0xCAFEBABE) {
  throw new IOException("Invalid Java class");
}
int minor = 0xFFFF & data.readShort();
int major = 0xFFFF & data.readShort();
System.out.println(major + "." + minor);
+6

Java: Java

:

public static final int JDK14_MAJOR_VERSION = 48;

public static final int JDK15_MAJOR_VERSION = 49;

public static final int JDK16_MAJOR_VERSION = 50;

Java , , JVM

+4

Byte 5 through 8 of the contents of the class file is the hexadecimal version number. You can use Java code (or any other language) to parse the version number.

+3
source

Source: https://habr.com/ru/post/1722430/


All Articles