How to check Java version used to compile a class

There are cases, when we try to use library with a higher supported version of Java than our application and as a result we get an exception like this:

java.lang.UnsupportedClassVersionError: TestedClass :
 Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)

or like that:

bad class file: TestedClass
class file has wrong version 55.0, should be 52.0
Please remove or make sure it appears in the correct subdirectory of the classpath.

Unfortunately, Java bytecode compiled on higher Java version isn’t compatible with older versions – you can’t run new code on old JVM.

How to identify compiled Java version

You can find out information about compiled Java version of conflicted class by running the following command:

 javap -verbose package.TestedClass

The javap disassembles provided class and prints its declarations of the non-private members. The output also contain compilation details, like version of Java used to compile:

minor version: 0
major version: 50

In case you don’t have available JDK to run javap, you can check the .class file manually. The information is stored in the file at the 7th byte. On Linux you can view file contents (in decimal byte values) using the command:

od -t u1 TheClass.class

The table below contains mapping of major version to JDK version

JVMMajor version
Java 1.1 45
Java 1.2 46
Java 1.3 47
Java 1.448
Java 549
Java 650
Java 751
Java 852
Java 953
Java 1054
Java 1155
Java 12 56
Java 1357
Java 1458

Solution

When you have information about Java version incompatibilities, there are two possible solutions:

Downgrading the library to lower version

If you are the owner of the dependency and the library is compatible with lower version of Java (there aren’t used any new features of newer specification) you can compile the library with older Java.

Upgrading the application to higher version

Upgrading your own application to the library version may be the best option. But in this case you should also be careful – you should check whether other dependencies are also compatible with the newer Java version.

Leave a Reply

Your email address will not be published. Required fields are marked *