Check compiled java version

How to find out the jdk version which compiled a class in java

You can easily determine the jdk version with which a given java file was compiled using the below command.

The above command should be executed at the location where the class file is placed or otherwise the entire path of class file needs to be given.

Open the command prompt on windows or terminal on linux/mac systems and navigate to the location of class file and execute the above command.
Example,

Note the folders com/codippa is the package of this class since a java file when compiled is located inside the folders that match its package.
This command will print a lengthy output which also contains the bytecode of the class but first few lines will let us know the version of jdk that we are looking for.
Above command prints the following output.

E:\com\codippa>javap -verbose HelloWorld.class
Classfile /E:/com/codippa/HelloWorld.class
Last modified 22-Jul-2019; size 1623 bytes
SHA-256 checksum 3300fe43abc2f26d1c5cf5e8870081c60e91d6cfd8d96f2fc8f18ce4660b151e
Compiled from “HelloWorld.java”
public class com.codippa.HelloWorld

flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: #1 // com/codippa/HelloWorld
super_class: #3 // java/lang/Object
interfaces: 0, fields: 0, methods: 3, attributes: 1
……
……

Note that the output contains the name and complete path of the java file, its compiled class file name with package and other details.

If you look at the highlighted part, you will see a minor version: 0 and major version: 52. Out of these two values, major version will help us to determine the compiling jdk version as per the table below.

Major Version JDK Version
58 Java SE 14
57 Java SE 13
58 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 JDK 1.4
47 JDK 1.3
46 JDK 1.2
45 JDK 1.1

As per this table, the class file shown above was compiled on Java 8.

Share if it’s worth .

Источник

Читайте также:  Letter spacing and word spacing in html

[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.

Источник

How to Check Java Version on Mac or Windows

Java runs many of the applications that we use daily. Many applications cannot run on older versions of Java. Hence, it is essential to know which version is installed on your system.

In this tutorial, learn how to check the Java version on your Mac or Windows system.

How to Check if Java is Installed and version on mac or windows

  • A system running macOS or Windows
  • Access to the command-line/terminal window
  • A version of Java installed

Check Java Version on Mac

You can find the version of Java on macOS by:

  • using the GUI (Mac’s System Preferences)
  • prompting for the version in the terminal window

Option 1: Check Java Version on Mac Using the GUI

To check the Java version on Mac without using the terminal by searching for the Java Control Panel in the System Preferences.

1. Click the Apple icon in the menu bar to open the drop-down menu and navigate to System Preferences.

Finding system preferences on Mac

2. A new window opens with various icons and settings. Find and click the Java icon to open the Java Control Panel.

Читайте также:  Загрузка нескольких изображений html

Opening the Java control panel on Mac os

3. Once the Java Control Panel opens, click the About button. A new window with Java version information should appear.

Finding the Java version on macOS from the system preferences

Option 2: Check Java Version on Mac Using the Terminal

If you prefer using the terminal, checking the Java version is a simple one-command process.

1. First, open the terminal. To do so, click the Spotlight Search button in the top-right of the screen.

Mac spotlight search button.

2. Type terminal in the search bar and open it by clicking on the icon in the search results.

Open terminal on Mac.

3. Once in the command line, run the command: java -version . The output should display the Java version installed on your MacOS.

java version 1.8.0_261 installed on macOS

To check the version of the primary Java compiler – javac (pronounced “java-see”) use the command:

Note: If you have a Linux system, refer to How To Check Java Version Installed On Linux.

Check Java Version on Windows

To check the Java version on a Windows computer, you can use:

Option 1: Check Java Version on Windows Using GUI

To find the Java version on your Windows without opening a terminal window, use the Control Panel.

1. Open the Windows menu in the bottom-left corner and type control panel in the search bar.

Searching for the control panel in the Windows start menu.

2. Find the Control Panel in the search results and click the icon to open it.

Opening the control panel on Windows

3. Move to the Programs directory.

screenshot of the Open programs directory in Windows

4. Find and click the Java icon to open the Java Control Panel.

example of opening the Java Control Panel

5. Once the control panel opens, click the About button.

Viewing information about the Java control panel

6. The About Java window should appear and display the Java version on your computer.

example output of java version 8 update 261 installed on windows

Option 2: Check Java Version on Windows Using Command Line

Another option to find the Java version on Windows is through the command line.

1. Open the Windows Start menu in the bottom-left corner and type cmd in the search bar.

Search for command prompt on Windows

2. Then, open the Command Prompt once it appears in the search results.

Open command prompt on Windows

3. A new window with the command prompt should appear. In it, type the command java -version and hit Enter. The output should display the Java version installed on your Windows system.

java version 1.8.0_261 installed on windows

You can also check the version of the Java’s primary compiler, javac, with the command:

This article showed you how to check the version of Java installed on a macOS or Windows system.

Источник

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

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

Читайте также:  Css занять оставшееся пространство

В следующем фрагменте кода демонстрируется запуск 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 для удобства чтения.

Источник

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