0

For a single class - we can work out the version of Java used to compile it:

javap -verbose className

I have a scenario where I need to scale this up to a jar file containing many classes and jar files.

My question is: Is there a way within a bash script to determine the java version required by a jar file containing class files and jar files?

2
  • A "jar file containing ... jar files"?
    – Jeff Holt
    Commented Nov 30, 2023 at 12:10
  • You can scan the class file or jar with THIS to avoid having to extract anything
    – g00se
    Commented Nov 30, 2023 at 14:24

2 Answers 2

2

You can extract the JAR file and check the MANIFEST.MF file, which contains information about the JDK used to build the JAR. The "Created-By" or "Build-Jdk" header in the MANIFEST.MF file stores the JDK version used to create the JAR

replace JarName.jar with your jar

here is the bash script to find the jdk version:

#!/bin/bash
jdk_version=$(unzip -p JarName.jar META-INF/MANIFEST.MF | grep "Created-By\|Build-Jdk")
echo $jdk_version
2
  • 1
    Note that the headers are not mandatory so it is not guaranteed that the JAR's MANIFEST file will contain Created-By or Build-Jdk. Refer to the [JAR] specification.
    – Abra
    Commented Dec 1, 2023 at 8:10
  • 1
    The JDK version used to build a jar file does not say anything about the minimum version required to run the jar file.
    – Holger
    Commented Apr 2 at 13:32
2

A JAR file is just a collection of files. It's not guaranteed that every .class file in the JAR was compiled with the same JDK version - although I believe that the chances of encountering such a JAR file are very slim. Nonetheless, the Java class [major] version number is always the seventh and eighth bytes in a .class file.

Assuming that all .class files in the JAR have the same version, you can use the jar command to extract a .class file from the JAR and read the bytes that contain the Java version.

Refer to https://en.wikipedia.org/wiki/Java_class_file for details of the Java .class file format.

Refer to [SO question] How to get only the first ten bytes of a binary file for how to read the first bytes of the .class file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.