What version of javac built my jar?

前端 未结 20 976
孤街浪徒
孤街浪徒 2020-11-27 09:48

How can I tell what version of the Java compiler was used to build a jar? I have a jar file, and it could have been built in any one of three JDKs. We need to know exactly

20条回答
  •  感动是毒
    2020-11-27 10:44

    Developers and administrators running Bash may find these convenience functions helpful:

    jar_jdk_version() {
      [[ -n "$1" && -x "`command -v javap`" ]] && javap -classpath "$1" -verbose $(jar -tf "$1" | grep '.class' | head -n1 | sed -e 's/\.class$//') | grep 'major version' | sed -e 's/[^0-9]\{1,\}//'
    }
    
    print_jar_jdk_version() {
      local version
      version=$(jar_jdk_version "$1")
      case $version in 49) version=1.5;; 50) version=1.6;; 51) version=1.7;; 52) version=1.8;; esac
      [[ -n "$version" ]] && echo "`basename "$1"` contains classes compiled with JDK version $version."
    }
    

    You can paste them in for one-time usage or add them to ~/.bash_aliases or ~/.bashrc. The results look something like:

    $ jar_jdk_version poi-ooxml-3.5-FINAL.jar
    49
    

    and

    $ print_jar_jdk_version poi-ooxml-3.5-FINAL.jar
    poi-ooxml-3.5-FINAL.jar contains classes compiled with JDK version 1.5.
    

    EDIT As jackrabbit points out, you can't 100% rely on the manifest to tell you anything useful. If it was, then you could pull it out in your favorite UNIX shell with unzip:

    $ unzip -pa poi-ooxml-3.5-FINAL.jar META-INF/MANIFEST.MF
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.7.1
    Created-By: 11.3-b02 (Sun Microsystems Inc.)
    Built-By: yegor
    Specification-Title: Apache POI
    Specification-Version: 3.5-FINAL-20090928
    Specification-Vendor: Apache
    Implementation-Title: Apache POI
    Implementation-Version: 3.5-FINAL-20090928
    Implementation-Vendor: Apache
    

    This .jar doesn't have anything useful in the manifest about the contained classes.

提交回复
热议问题