Checking java class version

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Library for listing version of Java class files.

License

fracpete/java-class-version

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Library for listing version of Java class files.

Collects the Java versions stored in class files and outputs it in various formats: text, CSV or summary (counts per version).

usage: com.github.fracpete.javaclassversion.ListClasses [-h] --input INPUT [--format ] [--output OUTPUT] [--verbose] Listing Java class file versions. named arguments: -h, --help show this help message and exit --input INPUT The files or directories to inspect --format The output format to use --output OUTPUT The file to write the generated output to --verbose Whether to be verbose during generation 

Add the following dependency to your pom.xml :

dependency> groupId>com.github.fracpetegroupId> artifactId>java-class-versionartifactId> version>0.0.1version> dependency>

About

Library for listing version of Java class files.

Источник

How to check the java compiler version from a java class file?

This tutorial provides a great way to find Java compiler version for a class file generated. It is one of the common problem among Java developers to know the exact version in which the JAR file is created. If you receive a JAR file, can you find what is the target compiler version for that JAR file to be deployed?. If developer not aware of the details, it is difficult for them to test the compatibility issues. If the run the code with different version, runtime exception will be thrown. Before start reading this article, If you want to understand the basics of Java compiler and JVM architecture, please go through the articles Java Compiler API, JVM, JRE and JDK difference and JVM.

java.lang.UnsupportedClassVersionError: test class : Unsupported major.minor version 51.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source)

Without knowing the Java version in which the JAR is created is difficult for the developers. There is no way to check the version in the JAR file itself. We can check the version details only using the class files inside the JAR file. Unzip the JAR and take out any one class file to be verified.

  • JDK 1.0 — major version 45 and minor version 3
  • DK 1.1 — major version 45 and minor version 3
  • JDK 1.2 — major version 46 and minor version 0
  • JDK 1.3 — major version 47 and minor version 0
  • JDK 1.4 — major version 48 and minor version 0
  • JDK 1.5 — major version 49 and minor version 0
  • JDK 1.6 — major version 50 and minor version 0
  • JDK 1.7 — major version 51 and minor version 0
Читайте также:  Python senior interview question

These version could be different for each implementation of the compiler. The above details are specific to Oracle/Sun JDK. JDK has javap command to find the version details.

You will find the following details displayed on the screen.

javap

javapThere is simple program which can get you the Java version details. Run the below program by passing the class file name as the arguments, this would return you the major version details.

package com; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class GetVersion < public static void main(String[] args) throws IOException < System.out.println(getVersionDetails(args[0])); >public static String getVersionDetails(String filename) throws IOException < String version = ""; DataInputStream stream = new DataInputStream(new FileInputStream(filename)); int magicBytes = stream.readInt(); if (magicBytes != 0xcafebabe) < System.out.println(filename + " is not a valid java file!"); >else < int minorVersion = stream.readUnsignedShort(); int majorVersion = stream.readUnsignedShort(); version = majorVersion + "." + minorVersion; >stream.close(); return version; > >

javap command returns the complete details of the bytecode. In that there is major version and minor version which is for identifying the Java version details. I hope this tutorial have provided nice tip on finding the version details for the Java class. If you have any more tips, please contact us, we will publish it in our website.

Reference Books:

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Источник

Checking java class version

  • Language
  • HTML & CSS
  • Form
  • Java interaction
  • Mobile
  • Varia
  • Language
  • String / Number
  • AWT
  • Swing
  • Environment
  • IO
  • JS interaction
  • JDBC
  • Thread
  • Networking
  • JSP / Servlet
  • XML / RSS / JSON
  • Localization
  • Security
  • JNI / JNA
  • Date / Time
  • Open Source
  • Varia
  • Powerscript
  • Win API & Registry
  • Datawindow
  • PFC
  • Common problems
  • Database
  • WSH & VBScript
  • Windows, Batch, PDF, Internet
  • BigIndex
  • Download
  • TS2068, Sinclair QL Archives
  • Real’s HowTo FAQ
  • Donate!
  • Funny 1
  • Funny 2
  • Funny 3
  • Funny 4
  • One line
  • Ascii Art
  • Deprecated (old stuff)

    Check the class version Tag(s): Environment

    About cookies on this site

    We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.

    The first 4 bytes are a magic number, 0xCAFEBABe, to identify a valid class file then the next 2 bytes identify the class format version (major and minor).

    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 51 0 1.7 52 0 1.8
    import java.io.*; public class ClassVersionChecker < public static void main(String[] args) throws IOException < for (int i = 0; i < args.length; i++) checkClassVersion(args[i]); >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 + ": " + major + " . " + minor); in.close(); > >
    > java ClassVersionChecker ClassVersionChecker.class ClassVersionChecker.class: 49 . 0

    magic
    The magic item supplies the magic number identifying the class file format; it has the value 0xCAFEBABE.

    minor_version, major_version
    The values of the minor_version and major_version items are the minor and major version numbers of this class file.Together, a major and a minor version number determine the version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m. Thus, class file format versions may be ordered lexicographically, for example, 1.5 < 2.0 < 2.1.

    A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.

    Источник

    [39] Check the JDK version on which a Java class was compiled

    If you are a Java developer, you would have seen this issue (or a similar one) at least once in your developer life:

    Unsupported major.minor version 51.0

    And the fix for this is pretty straightforward: either decrease the target runtime of the JDK or update the version of the JRE.

    Something that is related to this is about knowing the version of JDK on which a class file was compiled. Because, most of the classes or libraries that we use are not ours (i.e., third party).

    There is a simple command which helps us with this (on Windows):

    javap -v SomeJavaClass.class | findstr "major version"
    javap -v SomeJavaClass.class | grep "major version"

    Note: Make sure that $JAVA_HOME/bin is on $PATH before executing the above commands.

    As you can see, the output of the above command gives a number, with which you can identify the Java version on which that class was compiled. Refer to the below table:

    Major Version Java Version
    58 Java SE 14
    57 Java SE 13
    56 Java SE 12
    55 Java SE 11
    54 Java SE 10
    53 Java SE 9
    52 Java SE 8
    51 Java SE 7
    50 Java SE 6
    49 Java SE 5
    48 Java SE 1.4
    47 Java SE 1.3
    46 Java SE 1.2
    45 Java SE 1.1

    Major Version vs Java SE Version

    Result: So the above OracleDriver.class was compiled on Java SE 6.

    I learnt this from one of my colleagues at work and this has helped me tremendously several times whenever I play with different versions of Java in my applications.

    Источник

    Программное определение версии компиляции JDK для Java-класса

    Когда необходимо определить, какая версия JDK использовалась для компиляции конкретного файла Java .class , часто используется подход , заключающийся в использовании javap и поиске указанной «основной версии» в выходных данных javap . Я ссылался на этот подход в своем блоге Autoboxing, Unboxing и NoSuchMethodError , но опишу его более подробно здесь, прежде чем перейти к тому, как это сделать программно.

    В следующем фрагменте кода демонстрируется запуск javap -verbose класса конфигурации Apache Commons ServletFilterCommunication содержится в commons-configuration-1.10.jar .

    javapVerboseMajorVersion49CommonsConfiguration

    Я обвел «главную версию» на снимке экрана, показанном выше. Число, указанное после «основной версии:» (в данном случае 49), указывает, что версия JDK, используемая для компиляции этого класса, – J2SE 5 . На странице Википедии для файла классов Java перечислены цифры «основной версии», соответствующие каждой версии JDK:

    Основная версия Версия JDK
    52 Java SE 8
    51 Java SE 7
    50 Java SE 6
    49 J2SE 5
    48 JDK 1.4
    47 JDK 1.3
    46 JDK 1.2
    45 JDK 1.1

    Это простой способ определить версию JDK, использованную для компиляции файла .class , но это может оказаться утомительным, если сделать это для множества классов в каталоге или JAR-файлах. Было бы проще, если бы мы могли программно проверить эту основную версию, чтобы она могла быть записана в сценарии. К счастью, Java поддерживает это. Матиас Эрнст (Matthias Ernst ) опубликовал « Фрагмент кода: программный вызов javap », в котором он демонстрирует использование JavapEnvironment из JAR инструментов JDK для программного выполнения функциональности javap , но есть более простой способ определить конкретные байты файла .class которые указывают на версия JDK, используемая для компиляции.

    Базовый доступ к версии JDK, используемой для компиляции файла .class

    Следующий листинг кода демонстрирует минималистичный подход к доступу к версии JDK-компиляции файла .class .

    Код создает экземпляр FileInputStream в интересующем (предполагаемом) файле .class и этот FileInputStream используется для создания экземпляра DataInputStream . Первые четыре байта допустимого файла .class содержат цифры, указывающие, что это допустимый скомпилированный класс Java, и пропускаются. Следующие два байта читаются как неподписанные короткие и представляют младшую версию. После этого идут два наиболее важных байта для наших целей. Они также читаются как неподписанные короткие и представляют основную версию. Эта основная версия напрямую связана с конкретными версиями JDK. Эти значимые байты (magic, minor_version и major_version) описаны в Главе 4 («Формат файла класса») Спецификации виртуальной машины Java .

    В приведенном выше листинге кода «волшебные» 4 байта просто пропущены для удобства понимания. Однако я предпочитаю проверять эти четыре байта, чтобы убедиться, что они соответствуют ожидаемым для файла .class . Спецификация JVM объясняет, чего следует ожидать от этих первых четырех байтов: «Магический элемент предоставляет магическое число, идентифицирующее формат файла класса; оно имеет значение 0xCAFEBABE ». Следующий листинг кода пересматривает предыдущий листинг кода и добавляет проверку, чтобы убедиться, что данный файл находится в скомпилированном Java-файле .class . Обратите внимание, что проверка специально использует шестнадцатеричное представление CAFEBABE для удобства чтения.

    Источник

Оцените статью