Caused by java lang classnotfoundexception helloworld class

Java — не удалось найти или загрузить основной класс

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

 Error: Could not find or load main class ClassName.class Caused by: java.lang.ClassNotFoundException: ClassName.class 

1. Нет пакета

1.1 Обзоры простой Java Hello World, без пакета.

 # Compile Java source code C:projects> javac HelloWorld.java C:projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java # Run Java C:projects>java HelloWorld.class Error: Could not find or load main class HelloWorld.class Caused by: java.lang.ClassNotFoundException: HelloWorld.class 

Чтобы исправить это, запустите java ClassName без .class расширение.

 C:projects>java HelloWorld Hello World 

2. С пакетом

2.1 Простой Hello World и package это так же как com.mkyong

 package com.mkyong; public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World"); >> 
 # Compile Java source code C:projects> javac HelloWorld.java C:projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java C:projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.NoClassDefFoundError: com/mkyong/HelloWorld (wrong name: HelloWorld) 

2.2 Если package определяется, классы Java .class должен разместить в правильном месте папки.

Выше сгенерированный файл класса должен поместить в C:projectscommkyongHelloWorld.class

Читайте также:  Read only one line in file python

2.3 Чтобы исправить это , мы можем использовать -d указать, где разместить сгенерированные файлы классов.

 # Compile Java source code C:projects> javac -d . HelloWorld.java C:projects> dir 15/04/2019 02:01 PM com 15/04/2019 01:51 PM 161 HelloWorld.java C:projectscommkyongHelloWorld.class C:projectsHelloWorld.java 

2.4 Теперь мы можем бежать так java .HelloWorld

 C:projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld C:projects>java com.csharpcoderr.HelloWorld Hello World 

Рекомендации

Источник

Java – Could not find or load main class

To fix it, run java ClassName , without .class extension.

 C:\projects>java HelloWorld Hello World 

2. With Package

2.1 A simple Hello World and package it as com.mkyong

 package com.mkyong; public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World"); >> 
 # Compile Java source code C:\projects> javac HelloWorld.java C:\projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java C:\projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.NoClassDefFoundError: com/mkyong/HelloWorld (wrong name: HelloWorld) 

2.2 If package is defined, the Java classes .class must place in the correct folder location.

The above generated class file must place in C:\projects\com\mkyong\HelloWorld.class

2.3 To fix it, we can use -d to specify where to place generated class files.

 # Compile Java source code C:\projects> javac -d . HelloWorld.java C:\projects> dir 15/04/2019 02:01 PM com 15/04/2019 01:51 PM 161 HelloWorld.java C:\projects\com\mkyong\HelloWorld.class C:\projects\HelloWorld.java 

2.4 Now, we can run like this java .HelloWorld

 C:\projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld C:\projects>java com.mkyong.HelloWorld Hello World 

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Источник

IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException

As you can see the above class does not have any complication issues or syntax errors. There can be multiple reasons that you may get the error, below are some of the solutions that may work for you!

  • Make sure that the class name is correct.
  • Go to Menu: Build -> Re-Build Project.
  • Remove .idea directory from your project and restart IDE.
  • Go to Files: Invalidate Cache/ Restart.
  • Check your project has a out folder, if not create one, example: /Users/code2care/IdeaProjects/java-examples/out
  • Edit Build/Run Configurations and check if you have selected the correct Java class that has a main method.
  • Spring Boot + Redis Cloud Configuration and Setup Tutorial
  • Implementing Bubble Sort Algorithm using Java Program
  • Generate Maven Project Dependency Tree using MVN Command
  • Convert Collection List to Set using Java 8 Stream API
  • Java: RabbitMq Create a Queue Example
  • List of Java JDK Major Minor Version Numbers
  • 9 Ways to Loop Java Map (HashMap) with Code Examples
  • [fix] Java Spring Boot JPA SQLSyntaxErrorException: Encountered user at line 1 column 14
  • Project JDK is not defined [IntelliJ IDEA]
  • Deep Dive: Java Object Class from java.lang Package
  • Check if a Java Date String is Valid or Not (Java 8)
  • JdbcTemplate Batch Insert Example using Spring Boot
  • Convert JSON to Gson with type as ArrayList
  • [Fix] Java — Exception in thread main java.lang.IllegalThreadStateException
  • [Fix] Spring Boot: java.sql.SQLSyntaxErrorException: Unknown database
  • 7 deadly java.lang.OutOfMemoryError in Java Programming
  • List of jar files for Jax-ws (SOAP) based Java Web Services
  • Java get day of the week as an int using DayOfWeek
  • Add two numbers using Java Generics
  • Java Program to generate random string
  • Spring 5 IoC Example with application Context XML (ClassPathXmlApplicationContext) and Gradle.
  • [Java] How to throws Exception using Functional Interface and Lambda code
  • Error: Unable to access jarfile jarFileName.jar file [Windows]
  • Unhandled exception type InterruptedException : Java Threads
  • Fix: SyntaxError: ( was never closed [Python]

Know the Author: With a Masters Degree in Computer Science, Rakesh is a highly experienced professional in the field. With over 18 years of practical expertise, he specializes in programming languages such as Java, Python, Sharepoint, PHP, and Rust. He is dedicated to delivering high-quality solutions and providing valuable insights to meet the unique challenges of the digital landscape. rakesh@code2care.org is where you can reach him out.

We keep our articles short so the focus remains on providing effective tech solutions while promoting healthier screen habits and enhancing overall well-being. 📝 💡 🌱 By reducing screen time, we contribute to a greener future, reducing carbon emissions and fostering digital well-being. 🌍 🌿 🔋

We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity — #BlackLivesMatters

Источник

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.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

‘Could not find or load main class’ when running jar containing docker-java as dependency #1098

‘Could not find or load main class’ when running jar containing docker-java as dependency #1098

Comments

  1. Create basic gradle project with docker-java as a compile dependency
  2. Add a simple HelloWorld main class
  3. Run the gradle jar task
  4. java -jar hello-world.jar

Exception thrown at startup is

Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld 

Removing docker-java from compile dependencies fixes the issue.

dependencies < compile( "com.github.docker-java:docker-java:3.0.14" ) >task helloWorld(type: Jar) < manifest < attributes 'Main-Class': 'HelloWorld' >baseName = 'hello-world' from < configurations.compile.collect < it.isDirectory() ? it : zipTree(it) >> with jar > 

Reproduced with jdk8, jdk9, jdk10
Tested with docker-java versions 3.0.6 , 3.0.14 , 3.1.0-rc-4

The text was updated successfully, but these errors were encountered:

I have exactly the same issue. After including the docker-java as a compile dependency java can’t load my main class from the fat jar with a SecurityException «Invalid signature file digest for Manifest main attributes». Actually the same happens when I try to add the docker-client library. The reason was that the library’s signature files were copied into the META-INF of my fat jar and it broke class loading of my main class. Here is the fix:

 jar < manifest < attributes( "Main-Class" to "sandbox.MainKt" ) >from(configurations.compile.get().map < if (it.isDirectory) it else zipTree(it) >) from(configurations.runtimeClasspath.get().map < if (it.isDirectory) it else zipTree(it) >) exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA") > 

@sedovalx I’m facing this same exact problem but I’m new to this, so I’m not sure how would I go about using your fix. Could you elaborate a little on how to implement your fix? Thanks in advance

@dwgabriel the code fragment above is from my Gradle build script. It describes the configuration of the jar task that can be run with ./gradlew jar . The task assembles an executable jar file that can be executed with java -jar my-app.jar .

Build scripts in Gradle typically named as build.gradle (if written in Groovy) or build.gradle.kts (in case of Kotlin).

Still broken in 3.2.6 , same steps to reproduce, add dep. docker-java , build a fat jar, run with java -jar fat.jar :

dependencies < . implementation("com.github.docker-java:docker-java:3.2.6") >tasks.withType  < manifest < attributes["Main-Class"] = "com.company.application.Main" >configurations["compileClasspath"].forEach < file: File ->from(zipTree(file.absoluteFile)) > > 

Is an obscure workaround enough to consider this issue closed?

Источник

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