Error unable to initialize main class

Как исправить ошибку java.lang.NoClassDefFoundError в Java J2EE Я потратил довольно много времени, чтобы выяснить как исправить ошибку java.lang.NoClassDefFoundError в Java. В этой инструкции я покажу как исправить эти ошибки, раскрою некоторые секреты NoClassDefFoundError и поделюсь своим опытом в этой области. NoClassDefFoundError – это самая распространенная ошибка в разработке Java. В любом случае, давайте посмотрим, […]

Содержание

  1. Как исправить ошибку java.lang.NoClassDefFoundError в Java J2EE
  2. Разбираемся с причинами noclassdeffounderror в Java
  3. Разница между java.lang.NoClassDefFoundError и ClassNotFoundException в Java
  4. Примеры
  5. NoClassDefFoundError в Java из-за исключения в блоке инициализатора
  6. Fix Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  7. Java Program With the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  8. Possible Causes for Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  9. Solution to Eradicate the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  10. Ошибка Maven «Невозможно инициализировать основной класс» при попытке запустить только что созданный файл JAR
  11. 2 ответа
  12. java.lang.NoClassDefFoundError
  13. java.lang.NoClassDefFoundError
  14. NoClassDefFoundError Class Diagram
  15. java.lang.NoClassDefFoundError Reasons
  16. How to resolve java.lang.NoClassDefFoundError?

Как исправить ошибку java.lang.NoClassDefFoundError в Java J2EE

Я потратил довольно много времени, чтобы выяснить как исправить ошибку java.lang.NoClassDefFoundError в Java.

В этой инструкции я покажу как исправить эти ошибки, раскрою некоторые секреты NoClassDefFoundError и поделюсь своим опытом в этой области.

NoClassDefFoundError – это самая распространенная ошибка в разработке Java. В любом случае, давайте посмотрим, почему это происходит и что нужно сделать для разрешения проблемы.

Разбираемся с причинами noclassdeffounderror в Java

NoClassDefFoundError в Java возникает, когда виртуальная машина Java не может найти определенный класс во время выполнения, который был доступен во время компиляции.

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

Важно понимать, что это отличается от ClassNotFoundException, который появляется при попытке загрузить класс только во время выполнения, а имя было предоставлено во время выполнения, а не во время компиляции. Многие Java-разработчики смешивают эти две ошибки и запутываются.

NoClassDefFoundError возникнет, если класс присутствовал во время компиляции, но не был доступен в java classpath во время выполнения. Обычно появляется такая ошибка:

Разница между java.lang.NoClassDefFoundError и ClassNotFoundException в Java

[ads-pc-3]
java.lang.ClassNotFoundException и java.lang.NoClassDefFoundError оба связаны с Java Classpath, и они полностью отличаются друг от друга.

ClassNotFoundException возникает, когда JVM пытается загрузить класс во время выполнения, т.е. вы даете имя класса во время выполнения, а затем JVM пытается загрузить его, и если этот класс не найден, он генерирует исключение java.lang.ClassNotFoundException.

Тогда как в случае NoClassDefFoundError проблемный класс присутствовал во время компиляции, и поэтому программа успешно скомпилирована, но не доступна во время выполнения по любой причине.

Приступим к решению ошибки java.lang.NoClassDefFoundError.

Нам нужно добавить NoClassDefFoundError в Classpath или проверить, почему он не доступен в Classpath. Там может быть несколько причин, таких как:

  1. Класс недоступен в Java Classpath.
  2. Возможно, вы запускаете вашу программу с помощью jar, а класс не определен в атрибуте ClassPath.
  3. Любой сценарий запуска переопределяет переменную среды Classpath.
    Поскольку NoClassDefFoundError является подклассом java.lang.LinkageError, он также может появиться, если библиотека может быть недоступна.
  4. Проверьте наличие java.lang.ExceptionInInitializerError в файле журнала. NoClassDefFoundError из-за сбоя инициализации встречается довольно часто.
  5. Если вы работаете в среде J2EE, то видимость Class среди нескольких Classloader также может вызвать java.lang.NoClassDefFoundError.

Примеры

  1. Простой пример NoClassDefFoundError – класс принадлежит отсутствующему файлу JAR, или JAR не был добавлен в путь к классам, или имя jar было изменено кем-то.
  2. Класс не находится в Classpath, нет способа узнать это, но вы можете просто посмотреть в System.getproperty (“java.classpath”), и он напечатает classpath оттуда, где можно получить представление о фактическом пути к классам во время выполнения.
  3. Просто попробуйте запустить явно -classpath с тем классом, который, по вашему мнению, будет работать, и если он работает, это верный признак того – что-то переопределяет java classpath.

NoClassDefFoundError в Java из-за исключения в блоке инициализатора

Это еще одна распространенная причина java.lang.NoClassDefFoundError, когда ваш класс выполняет некоторую инициализацию в статическом блоке и если статический блок генерирует исключение, класс, который ссылается на этот класс, получит NoclassDefFoundError.

Смотрите в журнале java.lang.ExceptionInInitializerError, потому что это может вызвать java.lang.NoClassDefFoundError: Could not initialize class.

Как и в следующем примере кода, во время загрузки и инициализации класса, пользовательский класс генерирует Exception из статического блока инициализатора, который вызывает ExceptionInInitializerError при первой загрузке пользовательского класса в ответ на новый вызов User ().
[ads-pc-3]

  1. Поскольку NoClassDefFoundError также является LinkageError, который возникает из-за зависимости от какого-либо другого класса, вы также можете получить java.lang.NoClassDefFoundError, если ваша программа зависит от собственной библиотеки, а соответствующая DLL отсутствует. Помните, что это может также вызвать java.lang.UnsatisfiedLinkError: no dll in java.library.path. Чтобы решить эту проблему, держите dll вместе с JAR.
  2. Если вы используете файл ANT, создайте JAR, стоит отметить отладку до этого уровня, чтобы убедиться, что скрипт компоновки ANT получает правильное значение classpath и добавляет его в файл manifest.mf.
  3. Проблема с правами доступа к файлу JAR. Если вы работаете с Java-программой в многопользовательской операционной системе, такой как Linux, вам следует использовать идентификатор пользователя приложения для всех ресурсов приложения, таких как файлы JAR, библиотеки и конфигурации. Если вы используете разделяемую библиотеку, которая используется несколькими приложениями, работающими под разными пользователями, вы можете столкнуться с проблемой прав доступа, например, файл JAR принадлежит другому пользователю и недоступен для вашего приложения.
  4. Опечатка в конфигурации XML также может вызвать NoClassDefFoundError в Java. Как и большинство Java-фреймворков, таких как Spring, Struts все они используют конфигурацию XML для определения bean-компонентов. В любом случае, если вы неправильно указали имя компонента, он может вызвать ошибку при загрузке другого класса. Это довольно часто встречается в среде Spring MVC и в Apache Struts, где вы получаете множество исключений при развертывании файла WAR или EAR.
  5. Когда ваш скомпилированный класс, который определен в пакете, не присутствует в том же пакете во время загрузки, как в случае с JApplet.
  6. Еще одна причина- это нескольких загрузчиков классов в средах J2EE. Поскольку J2EE не использует стандартную структуру загрузчика классов, а зависит от Tomcat, WebLogic, WebSphere и т.д., от того, как они загружают различные компоненты J2EE, такие как WAR-файл или EJB-JAR-файл. Кроме того, если класс присутствует в обоих файлах JAR и вы вызовете метод equals для сравнения этих двух объектов, это приведет к исключению ClassCastException, поскольку объект, загруженный двумя различными загрузчиками классов, не может быть равным.
  7. Очень редко может происходить Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/tools/javac/Main. Эта ошибка означает, что либо ваш Classpath, PATH или JAVA_HOME не настроен должным образом, либо JDK установка не правильная. Попробуйте переустановить JDK. Замечено, что проблема возникала после установки jdk1.6.0_33 и последующей переустановки JDK1.6.0_25.

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

Источник

Fix Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Today, we will learn about another runtime error: the java.lang.noclassdeffounderror: could not initialize class . First, we will go through a Java program having this error which will lead to the discussion about possible reasons and figure out which line of code is causing this error.

Finally, we will also learn about the solution to eliminate this error.

Java Program With the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Here, we have two .java classes named PropHolder and Main . The PropHolder class loads the properties from the specified file while the Main class sets them and saves them into a file.

It also references the prop variable of the PropHolder class to print the values of all properties.

This Java code works fine when we run it on our local machine, but it does not work when deployed on a Linux Server with some script. Why is it so? Let’s figure out the reasons.

Possible Causes for Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Firstly, remember that getting the java.lang.NoClassDefFoundError does not only mean our class is missing. If that is so, we will get the java.lang.ClassNotFoundException .

It also does not mean that the bytecode ( .class ) is missing (in that case, we would get an error like this java.lang.NoClassDefFoundError: classname ).

So, the java.lang.noclassdeffounderror: could not initialize class error by our server means it cannot locate the class file. It can be caused by different reasons that are listed below.

The issue can be in the static block (also called a static initializer). It’d appear with an uncaught exception, occur & propagated up to an actual ClassLoader trying to load a class.

If the exception is not due to the static block, it can be while creating a static variable named PropHolder.prop .

Possibly, the Class is not available in the specified Java CLASSPATH .

We might have executed our Java program using the jar command while the Class was not defined in the ClassPath attribute of the MANIFEST file.

This error can be caused by a start-up script that overrides the CLASSPATH environment variable.

Another reason could be missing a dependency. For instance, the native library might not be available because NoClassDefFoundError is the child class of java.lang.LinkageError .

We can also look for the java.lang.ExceptionInInitializerError in our log file because there is a possibility that the NoClassDefFoundError was occurring due to the failure of static initialization.

If one of you is working in the J2EE environment, then the Class ’s visibility in different ClassLoaders can cause the java.lang.NoClassDefFoundError error.

Sometimes, it causes due to JRE/JDK version error.

It can also occur when we compile something on our machine with, let’s say, OpenJDK version 8.x.x. We push/commit, but someone else has configured its JAVA_HOME to some 11.x JDK version.

Here, we can get ClassNotFoundError , NoClassDefFoundError , etc. So, it is better to check what JDK the program has been compiled with.

Solution to Eradicate the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

In our case, the ClassLoader ran into the error while reading the class definition when it was trying to read the class. So, putting a try-catch block inside the static initializer will solve the issue.

Remember, if we are reading some files there, then it would differ from our local environment.

In the above class, we created a static variable named prop of type Properties , which we use in the static block. Inside the static block, we created an object of the FileInputStream , which obtains the input bytes from a specified file in the file system.

Next, we initialized the prop variable by calling the constructor of the Properties class, which is used to load the properties from a specified file. Remember, this static block only gets executed once we run the application.

In the Main class, we instantiate the Properties class to set values for various properties and save them in the specified file. Next, we reference the PropHolder.prop to access the values of db.url , db.user , and db.password properties and print them on the program output console as follows.

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Источник

Ошибка Maven «Невозможно инициализировать основной класс» при попытке запустить только что созданный файл JAR

Я создал файл .jar, используя Maven в командной строке. Он создал файл .jar. Когда я попытался запустить его в командной строке, я получил эту ошибку:

Я не уверен, как решить эту проблему. Это файловая структура, показывающая, где находятся важные файлы (пакет объединен для набора текста):

Мой pom.xml (Изменить: добавлен предложенный код)

Я также прочитал кое-что, что должно быть основным атрибутом манифеста, но я не уверен. Я хочу, чтобы люди могли запускать мою программу через банку, не полагаясь на то, что у них есть IDE.

2 ответа

Это коренная причина вашей проблемы:

Загрузчик классов не может найти класс WebDriver .

Возможно, потому что файл JAR, содержащий класс, не находится в пути времени выполнения .

Итак, как вы получаете это на пути к классам?

Используйте java -cp . com.aking.app.Application , где . содержит все нужные вам файлы JAR. документация Oracle объясняет необходимый синтаксис использовать для выражения пути к классам в командной строке.

Примечание. В Linux и Mac OS разделителем пути к классам является : , а не ; .

Измените свой JAR-файл, добавив в его файл MANIFEST.MF атрибут Class-Path .

Создайте «UberJAR», который содержит разнесенную копию всех зависимых JAR.

Вариации 2 и 3 можно сделать с помощью Maven.

Вы должны указать свой стартовый класс в pom.xml. В разделе свойств, включите строку ниже

Путь должен быть относительным, то есть с начала имени вашего пакета.

Источник

java.lang.NoClassDefFoundError

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

java.lang.NoClassDefFoundError is runtime error thrown when a required class is not found in the classpath and hence JVM is unable to load it into memory.

java.lang.NoClassDefFoundError

  • NoClassDefFoundError is a runtime error, so it’s beyond our application scope to anticipate and recover from this.
  • java.lang.NoClassDefFoundError is a runtime error, it never comes in compile time.
  • It’s very easy to debug NoClassDefFoundError because it clearly says that JVM was unable to find the required class, so check classpath configurations to make sure required classes are not missed.

NoClassDefFoundError Class Diagram

Below image shows NoClassDefFoundError class diagram and it’s super classes. As you can see that it’s super classes are Throwable and Error .

java.lang.NoClassDefFoundError Reasons

Let’s first try to replicate a scenario where we get NoClassDefFoundError at runtime. Let’s say we have a java classes like below.

Notice that above class doesn’t depend on any other custom java classes, it just uses java built-in classes. Let’s create another class that will use Data class in the same directory.

Now let’s compile DataTest class and then execute it like below.

So far everything is fine, now let’s move Data class files to somewhere else and then try to execute DataTest class. We will not compile it again since then it will give compilation error.

Here it is, we got NoClassDefFoundError because java runtime is unable to find Data class as clearly shown in the exception stack trace. Below image shows all the above commands and output in the terminal window.

How to resolve java.lang.NoClassDefFoundError?

From above example, we can clearly identify that the only reason for this error is that the required classes were available at compile time but not at runtime. You can fix NoClassDefFoundError error by checking following:

Check the exception stack trace to know exactly which class throw the error and which is the class not found by java.

Next step is to look for classpath configuration, sometimes we compile our classes in Eclipse or some other environment and run in some other environment and we can miss classpath configurations. For example, I can fix above issue easily by adding the directory which contains Data class to the classpath like below.

Remember that earlier I had moved Data class to previous directory.

Most of the times, NoClassDefFoundError comes with applications running on some server as web application or web services, in that case check if the required jars are part of the WAR file or not. For example, below maven configuration will not package jar file when generating WAR file.

But we need it for creating a servlet based web application, usually this jar is always part of Tomcat or any other application server.

That’s all for a quick look at java.lang.NoClassDefFoundError , I hope you find enough idea when this error comes and how to fix it easily. Reference: API Doc, Exception Handling in Java

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Источник

При попытке запуска класса Mainjava Main или запуска .jar файла java -jar Bot-1.jar, получаю ошибку

Error: Unable to initialize main class Main
Caused by: java.lang.NoClassDefFoundError: org/telegram/telegrambots/meta/exceptions/TelegramApiRequestException

Если запускать проект в Intellij idea, то все ок.

pom файл выглядит вот так:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <groupId>TestBot</groupId>
    <artifactId>Bot</artifactId>
    <version>1.0</version>
    <dependencies>


    <dependency>
        <groupId>org.telegram</groupId>
        <artifactId>telegrambots</artifactId>
        <version>4.9.1</version>
    </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.16</version>
        </dependency>

    </dependencies>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
    </properties>

</project>

Помогите пожалуйста решить проблему!
Правильно ли я понимаю, что ошибка возникает из за того что у меня локально отсутствует архив .jar telegrambots.meta? Почему он не скачивается автоматически при установке mvn install, ведь зависимость прописана в pom?
Куда мне нужно поместить библиотеки что бы собранный .jar запускался не только у меня локально но и при деплое, на пример, на herku?

Pb-BASS

7 / 7 / 2

Регистрация: 21.02.2019

Сообщений: 134

1

24.04.2019, 08:35. Показов 8347. Ответов 5

Метки нет (Все метки)


Доброго всем времни суток.
Помогите решить вот такую проблемку.
Установил среду Eclipse. В ней установил через Marketplace e(fx)eclipse.
Скачал javafx-sdk-11.0.2. Распаковал архив.
Пытаюсь создать JavaFX приложение. Среда создает стандартную заготовку:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package application;
    
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
 
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}

Но при попытке запуска получаю следующее сообщение:
Error: Unable to initialize main class application.Main
Caused by: java.lang.NoClassDefFoundError: Stage

Так же на строках импорта появляется сообщение:
The import javafx cannot be resolved

Попытался создать просто Java проект и импортировать в него необходимые библиотеки. Но и эта попытка завершилась неудачей.

Кто знает, в чем может быть причина?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



1227 / 844 / 260

Регистрация: 02.04.2009

Сообщений: 3,176

24.04.2019, 10:37

2



1



7 / 7 / 2

Регистрация: 21.02.2019

Сообщений: 134

24.04.2019, 12:53

 [ТС]

3

Kukstyler, спасибо.
Но столкнулся с такой проблемой.
В статье сказано, что требуется файл jfxrt.jar
Он у меня есть и лежит в папке jre1.8.0_211
Но, если я правильно понимаю, среда программирования использует JDK. А он лежит в папке jdk-12.0.1
Получается какая-то несовместимость,которую я никак не разберусь.

Добавлено через 1 час 18 минут
Через Windows — Preferences — Java — Installed JREs добавил jre1.8.0_211, но это проблему не решило. В чем может быть проблема, кто может подсказать?



0



1227 / 844 / 260

Регистрация: 02.04.2009

Сообщений: 3,176

24.04.2019, 13:02

4

Pb-BASS, посмотрите часть про Access Rules.



1



7 / 7 / 2

Регистрация: 21.02.2019

Сообщений: 134

24.04.2019, 13:10

 [ТС]

5

Цитата
Сообщение от Kukstyler
Посмотреть сообщение

посмотрите часть про Access Rules.

Сейчас перечитаю, но…
Я только что замен в разделе JRE System Library SDK12 на jre1.8 и проект стал работать. Но остался один вопрос.
Получается, что для компиляции и запуска проекта я сейчас использую утилиты из комплекта JRE. Но размве в состав JRE входит компилятор? Это е вроде только Java машина для запуска уже написанных программ. А для разработки требуется использовать JDK? Или я что-то путаю.



0




posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hi,

This is where I am at:   My project (J3-09) runs great on netbeans10 (JDK11) and my windows7 machine.

However, This is what I see at the command line:

C:dist2>java -jar J3-09.jar

Error: Unable to initialize main class REN.My_Frame

Caused by: java.lang.NoClassDefFoundError: org/apache/commons/math3/

linear/RealVector

I have 2 jar library files in the dist2 folder:    commons-math3-3.6.1.jar, and jssc.jar

My research indicates that my main class is not able to find the jar libraries.    

What is the best way to solve this ?

Note that a solution also needs to be deployable to my Ubuntu 18.04 machine.

Thank you

Roy


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Does the manifest file in the jar file have a Class-Path: entry?

Bartender

Posts: 242


posted 2 years ago


  • Likes 1
  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

If you’re using Maven, add the jar plugin:

(Add your own class instead of cli.Launcher)

And add the Maven Shade Plugin to create a full jar

(The name of this plugin is deceptive; it can shade, but the primary purpose is to build a jar that contains all your dependencies)

Add the compiler plugin:

And variables:

Finally, execute «maven package» and it will generate a jar in the target folder which will be runnable and contain all your dependencies. This is the easiest and most consistent way to create jar files.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

If you’re trying to put JARs within JARs, that does not work in standard Java. Only classes in the outer JAR get put into the application’s CLASSPATH.

If you want to include other JARs within an executable JAR, then you need to add some additional code to extend the CLASSPATH. The easiest way to do that is to let Maven build the executable JAR using its executable JAR mojo Maven will add the extra logic. Just a regulat Maven JAR build won’t do that, however, so you do need to build with the correct mojo.

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

The shade plugin that Zachary mentioned bundles the contents of all dependencies inside your own JAR, making it a so-called fat JAR. This will work without any other JAR files, because their contents are placed alongside your own classes.

R Nordstrom

Greenhorn

Posts: 26


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hi,

I opened J3-09.jar with 7-zip.   This is the contents of MANIFEST.MF

Manifest-Version: 1.0

Ant-Version: Apache Ant 1.10.4

Created-By: 11.0.2+9-LTS (Oracle Corporation)

X-COMMENT: Main-Class will be added automatically by build

Main-Class: REN.My_Frame

I do not see a Path-Class statement. Do I need one ?

Thank you

Roy

Marshal

Posts: 77297


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

R Nordstrom wrote:. . . This is the contents of MANIFEST.MF . . .

I presume it has an empty line at the end.

I do not see a Path-Class statement. Do I need one ?

Thank you

Roy

Do you mean classpath? You only need a classpath if you are dependent on some external resources.

Norm Radder

Rancher

Posts: 4911


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

If the other jar files are NOT inside of your jar file but are separate files that are in the same folder as your jar file, the Class-Path statement will allow the JVM to find and use them.

R Nordstrom

Greenhorn

Posts: 26


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I found a Class-Path line in a project jar from my NetBeans-8 projects.

This is what my manifest file contained:

Manifest-Version: 1.0

Ant-Version: Apache Ant 1.9.4

Created-By: 1.8.0_40-b26 (Oracle Corporation)

Class-Path: lib/jssc.jar lib/jna-4.1.0.jar lib/commons-math3-3.6.1.jar

X-COMMENT: Main-Class will be added automatically by build

Main-Class: REN.My_Frame

So now I need to figure out why Netbeans-10 is not adding this line, or modify my current project jar/manifest file.  

I am not sure how to do either of these, but at least I know what is wrong.  

Roy

Norm Radder

Rancher

Posts: 4911


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

It looks like the Class-Path statement is telling the JVM to look in the lib folder for the 3 jar files on the statement.  Your jar file would be in a folder that contained the lib folder.

R Nordstrom

Greenhorn

Posts: 26


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hi Every one,

I figured out the root problem.  Netbeans 9, 10 and early 11, have a bug.  When the clean/build is executed it does not add the appropriate Class-Path line to the manifest file.  Also it does not create the lib folder for your library jars.  This problem was solved in Netbeans 11.2.  By installing Netbeans 11.3 I now have a good command line launch in win7 and ubuntu 18.04.

Thank you

Roy


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Thanks for posting that, R! It’s useful information about Netbeans so I added this post to the Netbeans forum.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Zachary Griggs wrote://truncated to avoid full post quote

Although the topic is solved there’re several issues to address:

1) As the error message was not «could not find main class» but a classdefnotfound of a dependency the issue was obviously not caused by a missing main-class manifest attribut — so, why even mentoined it? Did you read and understood the problem? Or did you may only jzst copied in some pre-written default text of maybe many?

2) Although building a fat jar often at least «make things work» it’s far from an ideal solution. Aside from possible conflicts it can be compared to keep swallow painkillers instead of taking proper meds to cure: you’re just tinkering with the symptoms instead of fixing the cause.

3)

This is the easiest and most consistent way to create jar files.

Uhm, no, it isn’t. It’s neither easy nor consistent and hence shouldn’t be seen or used as such.

If you have an external lib within it’s own jar don’t mess with it but rather correctly reference it in the classpath.

Btw: This may work for a hobbyist dev — but most often licenses deny abusing their covered code that way on distribution. You just can’t ship a big fat jar couple 100mb in size.

Понравилась статья? Поделить с друзьями:
  • Error unable to get shsh blobs for this device recovery os root ticket
  • Error unable to get cib
  • Error unable to find vcvarsall bat
  • Error unable to find splash resources age of mythology что делать
  • Error unable to find library