Progress28.ru

IT Новости


09ae9cb0
2 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java lang unsupportedclassversionerror

Ошибка: Exception in thread «main» java

Если вы сталкивались с ошибками Exception in thread «main», то в этой статье я расскажу что это значит и как исправить ее на примерах.

При работе в среде Java, типа Eclipse или Netbeans, для запуска java-программы, пользователь может не столкнуться с этой проблемой, потому что в этих средах предусмотрен качественный запуск с правильным синтаксисом и правильной командой.

Здесь мы рассмотрим несколько общих java-исключений(Exceptions) в основных исключениях потоков, которые вы можете наблюдать при запуске java-программы с терминала.

Исключение в потоке java.lang.UnsupportedClassVersionError

Это исключение происходит, когда ваш класс java компилируется из другой версии JDK и вы пытаетесь запустить его из другой версии java. Рассмотрим это на простом примере:

Когда создаётся проект в Eclipse, он поддерживает версию JRE, как в Java 7, но установлен терминал Jawa 1.6. Из-за настройки Eclipse IDE JDK, созданный файл класса компилируется с Java 1.7.

Теперь при попытке запустить эту версию с терминала, программа выдает следующее сообщение исключения.

Если запустить версию Java1.7, то это исключение не появится. Смысл этого исключения – это невозможность компилирования java-файла с более свежей версии на устаревшей версии JRE.

Исключение java.lang.NoClassDefFoundError

Существует два варианта. Первый из них – когда программист предоставляет полное имя класса, помня, что при запуске Java программы, нужно просто дать имя класса, а не расширение.

Обратите внимание: если написать: .class в следующую команду для запуска программы — это вызовет ошибку NoClassDefFoundError. Причина этой ошибки — когда не удается найти файл класса для выполнения Java.

Второй тип исключения происходит, когда Класс не найден.

Обратите внимание, что класс ExceptionInMain находится в пакете com.journaldev.util, так что, когда Eclipse компилирует этот класс, он размещается внутри /com/journaldev/util. Следовательно: класс не найден. Появится сообщение об ошибке.

Исключение java.lang.NoSuchMethodError: main

Это исключение происходит, когда вы пытаетесь запустить класс, который не имеет метод main. В Java.7, чтобы сделать его более ясным, изменяется сообщение об ошибке:

Всякий раз, когда происходит исключение из метода main — программа выводит это исключение на консоль.

В первой части сообщения поясняется, что это исключение из метода main, вторая часть сообщения указывает имя класса и затем, после двоеточия, она выводит повторно сообщение об исключении.

Например, если изменить первоначальный класс появится сообщение System.out.println(10/0) ; Программа укажет на арифметическое исключение.

Методы устранения исключений в thread main

Выше приведены некоторые из распространенных исключений Java в потоке main, когда вы сталкиваетесь с одной из следующих проверок:

  1. Эта же версия JRE используется для компиляции и запуска Java-программы.
  2. Вы запускаете Java-класс из каталога классов, а пакет предоставляется как каталог.
  3. Ваш путь к классу Java установлен правильно, чтобы включить все классы зависимостей.
  4. Вы используете только имя файла без расширения .class при запуске.
  5. Синтаксис основного метода класса Java правильный.

Средняя оценка / 5. Количество голосов:

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

java.lang.Unsupported >04.03.2012, 15:54. Просмотров 12753. Ответов 16

Добрый день! У меня проблемы в запуске файлов. Хотела запустить сервер и клиент на cmd. Он нормально компилируется и class файл появляется. Но когда пишу java Server.java уже выдает ошибку:

C:Users777>java Server
Exception in thread «main» java.lang.UnsupportedClassVersionError: Serve
pported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Server. Program will exit.

Как исправить ошибку? Уверена с кодом все в порядке. Наверняка дело связано с версией Java. или что-то типа этого. помогите

Добавлено через 17 минут
а не уже не надо все исправила

04.03.2012, 15:54

Java.lang.ClassCastException: MyBaza.Diag cannot be cast to java.lang.Comparable
Подскажите как исправить. Exception in thread «AWT-EventQueue-0» java.lang.ClassCastException.

Exception in thread «main» java.lang.NoClassDefFoundError:c:HelloWorldApp/java
Exception in thread ‘main’ java.lang.NoClassDefFoundError:c:HelloWorldApp/java вот это выходит.

java.lang.OutOfMemoryError
java.lang.OutOfMemoryError — иногда выдается (очень редко) непонятно почему. Можно что-то.

05.03.2012, 15:56205.03.2012, 20:50 [ТС]307.03.2012, 12:07409.01.2013, 10:365

Возникла такая же ситуация, замечание Skipy принял к сведению, но как это исправить не в курсе.

C:Program FilesJavaCoreJavaBookv1ch2Welcome>javac Welcome.java
C:Program FilesJavaCoreJavaBookv1ch2Welcome>java Welcome
Exception in thread «main» java.lang.UnsupportedClassVersionError: Welcome (Unsupported major.minor version 50.0)

at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)

Я установил на комп JDK6 http://www.oracle.com/technetwork/ja. s-1859587.html скачав «jdk-6u37-windows-i586.exe» предварительно снеся с машины всю Java, которая была до этого. В “PATH” прописал «C:Program FilesJavajdk1.6.0_37bin». Пока чуда нет: где и что нужно изменить?

Добавлено через 3 минуты
не знаю, ответит ли мне здесь кто-то или лучше создать новую тему? Новая тема — заметней, но плодить то же самое не хотел бы.

Читать еще:  Bufferedreader в java

Добавлено через 15 часов 49 минут
В разделе «Program Files» после установки JDK6 (Update 37) появилась папка Java с подпапками «jdk1.6.0_37» (C:Program FilesJavajdk1.6.0_37) и «jre6» (C:Program FilesJavajre6 со всеми требуемыми файлами), а в панели Управления иконка Java (посмотрел, Version 6 Update 37 (build 1.6.0_37-b06)). Т.е. я что хочу сказать: теоретически и та ява которая компилирует (я так понимаю, это и есть JDK6 (Update 37)) и та которая исполняет, т.е. JVM (выведенная в виде иконки в панели управления) есть обе шестые явы с одинаковым апдейтом, тем не менее ни хрена не запускается. Описал примитивно, но думаю доступно. Как быть?

How to resolve java.lang.Unsupported >

java.lang.UnsupportedClassVersionError is a quite common error after NoClassDefFoundError or ClassNotFoundException they all seems to related to class files but they all are different and there cause and resolution are different. In this java tutorial we will see what is UnsupportedClassVersionError in Java? Why UnsupportedClassVersionError comes in Java? What is class file format and version numbers associated with it and finally how to resolve UnsupportedClassVersionError in Java.

This article is in continuation of debugging tutorials like How to remote debug Java program in Eclipse and 10 Java debugging tips in Eclipse. If you have not read those article you may find them useful.

How to resolve UnsupportedClassVersionError in Java

What is UnSupportedClassVersionError in Java?

Java.lang.UnsupportedClassVersionError is a subclass of java.lang.ClassFormatError. This is a kind of linking error which occurs during linking phase accordingly java.lang.ClassFormatError has also derived from java.lang.LinkageError. As the name suggests «UnSupportedClassVersionError» so it’s related to unsupported class version, now questions comes what is class version in Java? Well every source file is compiled into class file and each class file has two versions associated with it, major version and minor version.

The Version of class file is represented as major_version.minor_version. This version is used to determine format of class file in Java.

According to Java Virtual Machine specification, “A JVM 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 JVM implementation conforming to a certain release level of the Java platform may support.” For example: JDK 1.2 supports class file formats from version 45.0 to version 46.0 inclusive. So if a class file has version 48.0 it means that major version of class file is «48» and minor version is «0», which tells us that JDK 1.4 has been used to compile and generate that class file.

When UnSupported >So now we got the theory behind class file format and major and minor version of class file in Java. Now a million dollar question is when UnSupportedClassVersionError in Java does occur? precise answer of this is «When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError and it generally occurs if a higher JDK version is used to compile the source file and a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error «java.lang.UnsupportedClassVersionError: Bad version number in .class file [at java.lang.ClassLoader.defineClass1(Native Method)]».

But its important to note is that vice-versa is not true «you can compile your program in J2SE 1.4 and run on J2SE 1.5 and you will not get any UnSupportedClassVersionError». When a higher JDK is used for compilation it creates class file with higher version and when a lower JDK is used to run the program it found that higher version of class file not supported at JVM level and results in java.lang.UnsupportedClassVersionError.

How to fix UnSupported >Now we know the root cause of UnSupportedClassVersionError that we are using a lower JVM for running the program. But major problem is that stack trace of UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class file could be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:

You can go by any approach to resolve UnSupportedClassVersionError based upon your need. Generally a higher JVM version is ok and does not cause any problem unless the class file format is quite old and no more supported by Sun in higher JVMs. The best way to deal with UnSupportedClassVersionError in Java is to use same version or JDK and JRE for compiling and running your program.

Example of UnSupported >You can easily reproduce UnSupportedClassVersionError by using javac of higher JDK and «java» from lower Java version. Let’s see some of examples of UnSupportedClassVersionError in Java:

1) java.lang.UnsupportedClassVersionError: EquityTradingManager (Unsupported major.minor version 49.0)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
==>Since we know that major version 49 is supported by JDK 1.5, so these will «java.lang.UnsupportedClassVersionError” will come if JVM used to run this program is lower than Java 1.5.

2) Java.lang.UnsupportedClassVersionError: Bad version number in .class file

3) java.lang.unsupportedclassversionerror unsupported classversion 50.0
==> Compile in JDK 1.6 and running on lower version than Java 6.

4) java.lang.unsupportedclassversionerror unsupported classversion 49.0
==> compiled in Java 5 and running on lower JVM than JDK 5.

5) java.lang.unsupportedclassversionerror bad version number in eclipse.

==> Most of us use eclipse for building and running project some of us also use ant for building project. In eclipse there is some setting related to java source version which if you got incorrect can result in «java.lang.unsupported > Properties ==> Java Compiler as shown in image

Important point about UnSupported >1) If you encounter UnSupportedClassVersionError, check the JRE version you are using to run program and switch to higher version for quick solution.
2) java.lang.UnsupportedClassVersionError is derived from java.lang.LinkageError, so it will not be detected in compile time and it will only come on runtime, precisely when JVM tries to load a class.
3) Class file format which is identified using major version and minor version. Class file format is assigned when you compile source file and its depends on JDK version used to compile.
4) Its always best practice to use same version of java for compilation and execution to avoid any chance of UnSupportedClassVersionError.
5) UnSupportedClassVersionError is not related to java classpath , so don’t confuse this with NoClassDefFoundError or ClassNotFoundException.

Major >Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

You can also get version of «javac» (used for compilation) and version of «java» (used for execution) as below
C:equity tradingstocks>javac -version
javac 1.6.0-beta2

C:equity tradingstocks>java -version
java version «1.6.0-beta2»
Java(TM) SE Runtime Environment (build 1.6.0-beta2-b86)
Java HotSpot(TM) Client VM (build 1.6.0-beta2-b86, mixed mode, sharing)

Now you can identify your JDK version based on class file format version whenever you see java.lang.UnsupportedClassVersionError 🙂

So next time when you see UnsupportedClassVersionError don’t be afraid and follow the best approach based upon your need.

How to Fix java.lang.Unsupported >Last modified: March 17, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Introduction

In this short tutorial, we’re going to learn what causes the Java runtime error java.lang.UnsupportedClassVersionError: Unsupported major.minor version and how to fix it.

2. A Look at the Error

Let’s start by looking at an example error:

This error is telling us that our class was compiled at a higher version of Java than the version with which we tried to run it. More specifically, in this case, we compiled our class with Java 11 and tried to run it with Java 8.

2.1. Java Version Numbers

For reference, let’s take a quick look at the Java version numbers. This will come in handy in case we need to download the appropriate Java version.

The major and minor version numbers are stored in the class bytecode at bytes six and seven.

Let’s see how the major version numbers map to Java versions:

  • 45 = Java 1.1
  • 46 = Java 1.2
  • 47 = Java 1.3
  • 48 = Java 1.4
  • 49 = Java 5
  • 50 = Java 6
  • 51 = Java 7
  • 52 = Java 8
  • 53 = Java 9
  • 54 = Java 10
  • 55 = Java 11
  • 56 = Java 12
  • 57 = Java 13

3. Fix via the Command Line

Let’s now discuss how we can resolve this error when running Java from the command line.

Depending on our situation, we have two ways we can resolve this error: compile our code for an earlier version of Java, or run our code on a newer Java version.

The final decision depends on our situation. If we need to use a third-party library that’s already been compiled at a higher level, our best option is probably to run our application using a newer Java version. If we’re packaging an application for distribution, it might be best to compile down to an older version.

3.1. JAVA_HOME Environment Variable

Let’s start by checking how our JAVA_HOME variable is set. This will tell us which JDK is being used when we run javac from our command line:

If we’re ready to move entirely to a newer JDK, we can download the newer version and make sure our PATH and JAVA_HOME environment variables are set appropriately.

3.2. Running a New JRE

Returning to our example, let’s look at how we can resolve the error by running it at a higher version of Java. Assuming we have Java 11 JRE in C:Appsjdk-11.0.2, we can run our code with the java command packaged with it:

3.3. Compiling with an Older JDK

If we’re writing an application that we want to be runnable down to a certain version of Java, we need to compile the code for that version.

We can do that in one of three ways: using an older JDK to compile our code, using the -bootclasspath, -source, and -target options of the javac command (JDK 8 and older), or using the –release option (JDK 9 and newer).

Let’s start by using an older JDK, similarly to how we used a newer JRE for running our code:

It’s possible to just use -source and -target, but it might still create class files that aren’t compatible with an older Java.

To ensure compatibility, we can point -bootclasspath at the rt.jar of the targeted JRE:

The above applies mainly to JDK 8 and lower. In JDK 9, the –release parameter was added to replace -source and -target. The –release option supports targets 6, 7, 8, 9, 10, and 11.

Let’s use –release to target Java 8:

Now we can run our code on a Java 8 or higher JRE.

4. Eclipse >

Now that we understand the error and the general approach to correcting it, let’s take what we’ve learned and see how we can apply it when working in the Eclipse IDE.

4.1. Changing the JRE

Assuming we already have Eclipse configured with different versions of Java, let’s change our project’s JRE.

Let’s go to our Project properties, then to Java Build Path, and then the Libraries tab. Once there, we’ll select the JRE and click Edit:

Now, let’s choose Alternate JRE and point to our Java 11 installation:

At this point, our application will run against Java 11.

4.2. Changing the Compiler Level

Let’s now look at how we can change our target to a lower level of Java.

First, let’s go back to our Project properties, then Java Compiler, and check Enable project specific settings:

Here, we can set our project to compile for earlier versions of Java and customize other compliance settings:

5. IntelliJ >

We can also control the version of Java we’re using for compiling and running in IntelliJ IDEA.

5.1. Adding a JDK

Before we do that, we’ll see how to add additional JDKs. Let’s go to File -> Project Structure -> Platform Settings -> SDKs:

Let’s click the plus icon in the middle column, select the JDK from the drop-down, and select our JDK location:

Now, when we run our project, it will run with the Java 11 JRE.

5.3. Changing the Compiler Level

If we’re distributing our application to run on a lower JRE, we need to adjust our compiler level to target the older version of Java.

Let’s go to File -> Project Structure… -> Project Settings -> Project and change our Project SDK and Project language level:

We can now build our project, and the class files generated will run on Java 8 and higher.

6. Maven

When we build and package a file in Maven, we can control the version of Java we target.

When using Java 8 or older, we set the source and target for the compiler plugin.

Let’s set the source and target using compiler plugin properties:

Alternatively, we can set the source and target in the compiler plugin:

With the –release option added in Java 9, we can configure that with Maven as well.

Let’s use a compiler plugin property to set the release:

Or we can configure the compiler plugin directly:

Ссылка на основную публикацию