gpt4 book ai didi

Why am I getting a NoClassDefFoundError in Java?(为什么在Java中会出现NoClassDefFoundError?)

转载 作者:bug小助手 更新时间:2023-10-26 19:37:48 34 4
gpt4 key购买 nike



I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?

当我运行Java应用程序时,出现NoClassDefFoundError。这通常是什么原因造成的?


更多回答

I believe it can also happen if you don't run your java program with the correct syntax. For instance, you have to call your class from the root bin folder with the full package name (ie. my.package.myClass). I'd be more specific if I could but I'm not much of a java guy. I just remember messing this up a few times.

我相信,如果您没有使用正确的语法运行您的Java程序,也会发生这种情况。例如,您必须从根bin文件夹中使用完整的包名(即.My.Package.myClass)。如果可以的话,我会说得更具体一些,但我不太喜欢Java。我只记得有几次把事情搞砸了。

优秀答案推荐

While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.

虽然这可能是由于编译时和运行时之间的类路径不匹配造成的,但这并不一定是真的。



It is important to keep two or three different exceptions straight in our head in this case:

在这种情况下,在头脑中记住两到三个不同的例外是很重要的:




  1. java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.


  2. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.




This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

当您的代码依赖于某个类文件,并且它在编译时存在但在运行时找不到时,就会出现这种情况。查找构建时间和运行时类路径之间的差异。



Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.

下面是演示java.lang.NoClassDefFoundError的代码。有关详细解释,请参阅Jared的回答。



NoClassDefFoundErrorDemo.java

NoClassDefFoundErrorDemo.java



public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}

}


SimpleCalculator.java

SimpleCalculator.java



public class SimpleCalculator {
static int undefined = 1 / 0;
}


NoClassDefFoundError In Java

Java中的NoClassDefFoundError



Definition:

定义:




  1. Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.


  2. If a class was present during compile time but not available in java classpath during runtime.




enter image description here



Examples:

例如:




  1. The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.

  2. A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.


  3. Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.


  4. Permission issue on JAR file can also cause NoClassDefFoundError in Java.

  5. Typo on XML Configuration can also cause NoClassDefFoundError in Java.

  6. when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.



Possible Solutions:

可能的解决方案:




  1. The class is not available in Java Classpath.

  2. If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

  3. Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.

  4. Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.

  5. Any start-up script is overriding Classpath environment variable.

  6. You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.



Resources:

资源:



3 ways to solve NoClassDefFoundError

解决NoClassDefFoundError的3种方法



java.lang.NoClassDefFoundError Problem patterns

Java.lang.NoClassDefFoundError问题模式



I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

我发现,当使用运行时发现的类的不兼容版本编译代码时,有时会出现NoClassDefFound错误。我记得的具体实例是使用ApacheAxis库。实际上,在我的运行时类路径上有2个版本,它拾取的是过时和不兼容的版本,而不是正确的版本,这导致了NoClassDefFound错误。这是在一个命令行应用程序中,我使用了一个类似于此的命令。



set classpath=%classpath%;axis.jar


I was able to get it to pick up the proper version by using:

通过使用以下命令,我能够让它获取正确的版本:



set classpath=axis.jar;%classpath%;


This is the best solution I found so far.

这是我到目前为止找到的最好的解决方案。



Suppose we have a package called org.mypackage containing the classes:

假设我们有一个名为org.mypackage的包,其中包含以下类:




  • HelloWorld (main class)

  • SupportClass

  • UtilClass



and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

定义这个包的文件物理上存储在目录D:\myprogram(在Windows上)或/home/user/myprogram(在Linux上)下。



The file structure will look like this:
enter image description here

文件结构如下所示:



When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
enter image description here

当我们调用Java时,我们指定要运行的应用程序的名称:org.mypackage.HelloWorld。但是,我们还必须告诉Java在哪里查找定义我们的包的文件和目录。因此,要启动该程序,我们必须使用以下命令:



One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:

在一个有趣的案例中,您可能会看到很多NoClassDefFoundErrors:




  1. throw a RuntimeException in the static block of your class Example

  2. Intercept it (or if it just doesn't matter like it is thrown in a test case)

  3. Try to create an instance of this class Example





static class Example {
static {
thisThrowsRuntimeException();
}
}

static class OuterClazz {

OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}

new Example(); //this throws NoClassDefFoundError
}
}


NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.

NoClassDefError将与ExceptionInInitializerError一起从静态块RuntimeException中抛出。






This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.

当您在单元测试中看到NoClassDefFoundErrors时,这一点尤其重要。



In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.

在某种程度上,您是在测试之间“共享”静态块执行,但初始ExceptionInInitializerError将只在一个测试用例中。第一个使用有问题的Example类的。其他使用Example类的测试用例将只抛出NoClassDefFoundErrors。



I was using Spring Framework with Maven and solved this error in my project.

我在Maven中使用了Spring框架,并在我的项目中解决了这个错误。



There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.

类中存在运行时错误。我将属性作为整数读取,但当它从属性文件读取值时,它的值是双精度的。



Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.

Spring没有给我运行时在哪一行出现故障的完整堆栈跟踪。它只显示NoClassDefFoundError。但当我将其作为本机Java应用程序执行时(将其从MVC中移除),它给出了ExceptionInInitializerError,这是真正的原因,也是我跟踪错误的方式。



@xli's answer gave me insight into what may be wrong in my code.

@XLI的回答让我洞察到我的代码中可能存在的错误。



I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.

当运行时类加载器加载的类不能访问Java RootLoader已经加载的类时,我会得到NoClassFoundError。因为不同的类加载器位于不同的安全域(根据Java),所以JVM不允许在运行时加载器地址空间中解析已经由根加载器加载的类。



Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'

使用‘Java-javaagent:tracer.jar[您的Java参数]’运行程序



It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.

它生成的输出显示加载的类以及加载类的加载器环境。跟踪类无法解析的原因非常有用。



// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5

import java.lang.instrument.*;
import java.security.*;

// manifest.mf
// Premain-Class: ClassLoadTracer

// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class

// java -javaagent:tracer.jar [...]

public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);

// dump stack trace of the thread loading class
Thread.dumpStack();

// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}


The technique below helped me many times:

下面的技巧帮了我很多次:



System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());


where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.

其中,TheNoDefFoundClass是由于偏爱您的程序使用的同一库的较旧版本而可能“丢失”的类。这种情况最常见,当客户端软件被部署到一个占主导地位的容器中时,该容器配备了自己的类加载器和大量最流行的库的旧版本。



Java ClassNotFoundException vs NoClassDefFoundError

Java ClassNotFoundException与NoClassDefFoundError


[ClassLoader]

[ClassLoader]


Static vs Dynamic class loading

静态与动态类加载


Static(Implicit) class loading - result of reference, instantiation, or inheritance.

静态(隐式)类加载-引用、实例化或继承的结果。


MyClass myClass = new MyClass();

Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()

动态(显式)类加载是Class.forName()、loadClass()、findSystemClass()


MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

Every class has a ClassLoader which uses loadClass(String name); that is why

每个类都有一个使用loadClass(字符串名)的ClassLoader;这就是为什么


explicit class loader uses implicit class loader

NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.

NoClassDefFoundError是显式类加载器的一部分。保证在编译期间显示了这个类,但现在(在运行时)却没有它,这是错误的。


ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.

ClassNotFoundException是隐式类加载器的一部分。对于另外可以使用它的场景来说,弹性是例外--例如,反射。



In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.

如果你有生成代码(EMF等)可能有太多的静态初始化器,其消耗了所有堆栈空间。



See Stack Overflow question How to increase the Java stack size?.

请参阅堆栈和溢出问题如何增加Java堆栈大小?



Two different checkout copies of the same project



In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.

在我的例子中,问题是Eclipse无法区分同一项目的两个不同副本。我有一个锁定在主干上(SVN版本控制),另一个一次在一个分支中工作。我尝试将工作副本中的一个更改作为JUnit测试用例,其中包括将私有内部类提取为其本身的公共类,并且在它工作时,我打开项目的另一个副本以查看需要更改的代码的其他部分。在某个时刻,NoClassDefFoundError弹出,抱怨私有内部类不在那里;在堆栈跟踪中双击会将我带到错误项目副本中的源文件。



Closing the trunk copy of the project and running the test case again got rid of the problem.

关闭项目的主干副本并再次运行测试用例可以消除问题。



I fixed my problem by disabling the preDexLibraries for all modules:

我通过禁用所有模块的preDexLibrary修复了问题:



dexOptions {
preDexLibraries false
...


I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.

当我将另一个模块的Maven依赖项添加到我的项目中时,我得到了这个错误,这个问题最终通过将-Xss2m添加到我的程序的JVM选项中得到了解决(从JDK5.0开始它默认是1兆字节)。人们认为该程序没有足够的堆栈来加载类。



In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.

在我的例子中,由于JDK版本不匹配,我收到了这个错误。当我试图从Intelij运行应用程序时,它不工作,但后来从命令行运行它工作了。这是因为Intelij试图用设置的Java 11 JDK运行它,但在命令行上它是用Java 8 JDK运行的。在文件>项目结构>项目设置>项目SDK下切换该设置后,它对我起作用了。



Update [https://www.infoq.com/articles/single-file-execution-java11/]:

更新[https://www.infoq.com/articles/single-file-execution-java11/]:



In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).




NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

当静态初始值设定项试图加载在运行时不可用的资源包时,也可能发生NoClassDefFoundError,例如受影响的类试图从META-INF目录加载但不在那里的属性文件。如果您没有捕获NoClassDefFoundError,有时您将无法看到完整的堆栈跟踪;要克服这一问题,您可以临时使用Throwable的CATCH子句:


try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}


I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.

在Tomcat/JBoss服务器上部署应用程序时,我遇到了NoClassDefFoundError。我尝试了不同的依赖项来解决问题,但总是得到相同的错误。将所有的javax.*依赖项标记为pom.xml中提供的依赖项,而WAR实际上没有依赖项。尽管如此,这个问题还是不断涌现。


Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.

最后,我意识到src/main/webapp/WEB-INF/CLASSES的CLASSES文件夹正在被复制到我的WAR中,所以这个类被复制,而不是被编译的类被复制,因此没有依赖项更改来解决问题。


Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..

因此,如果正在复制任何以前编译的数据,请注意,在删除类文件夹并重新编译后,它起作用了!



If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.

如果有人因为java.lang.NoClassDefFoundError:org/apache/log4j/Logger错误而来到这里,在我的例子中,它是因为我使用了log4j 2(但我没有添加它附带的所有文件)而产生的,而一些依赖库使用了log4j 1。解决方案是添加Log4j 1.x桥:与log4j 2一起提供的jar log4j-1.2-api-<版本>.jar。



This error can be caused by unchecked Java version requirements.

此错误可能由未经检查的Java版本要求引起。



In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.

在我的例子中,在构建一个备受瞩目的开源项目时,通过使用SDKMAN!从Java 9切换到Java 8,我能够解决这个错误。



sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu


Then doing a clean install as described below.

然后执行如下所述的全新安装。






When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.

当使用Maven作为构建工具时,在禁用测试的情况下执行干净的“安装”构建有时是有帮助的,而且通常是令人满意的。



mvn clean install -DskipTests


Now that everything has been built and installed, you can go ahead and run the tests.

现在一切都已构建和安装完毕,您可以继续运行测试了。



mvn test


I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.

当我没有在项目的Java构建路径中的“Order and Export”选项卡上导出类时,我收到了NoClassDefFound错误。确保在“Order and Export”选项卡中勾选添加到项目构建路径的任何依赖项。请参见Eclipse警告:XXXXXXXXXXX.jar将不会被导出或发布。可能会导致运行时ClassNotFoundExceptions。



It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.

这也可能是因为您从IDE中复制了具有特定包名称的代码文件,并且您希望尝试使用终端运行它。您必须首先从代码中删除包名称。我也是这样。



Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).

这里每个人都在谈论一些Java配置的东西,JVM问题等等,在我的例子中,错误根本与这些主题无关,有一个非常琐碎和容易解决的原因:我在我的控制器(Spring Boot应用程序)的终结点有一个错误的注释。



I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

在使用Liberty服务器的JavaEE中,我遇到了一个关于NoClassDefFoundError的有趣问题。我使用的是IMS资源适配器,而我的server.xml已经有了用于imudbJXA.rar的资源适配器。当我为imsubXA.rar添加新的适配器时,对于DLIException、IMSConnectionSpec或SQLInteractionSpec的实例对象,我会开始收到此错误。我不知道为什么,但我解决了这个问题,只使用imudbXA.rar为我的工作创建了新的server.xml。我确信在server.xml中使用多个资源适配器是可以的,我只是没有时间研究这一点。



I had this error but could not figure out the solution based on this thread but solved it myself.

我犯了这个错误,但基于这个帖子找不出解决方案,但我自己解决了它。


For my problem I was compiling this code:

对于我的问题,我编译了以下代码:


package valentines;

import java.math.BigInteger;
import java.util.ArrayList;

public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE

}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}

}

I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver

然后,我在一个类似/ProjectName/valentines的文件夹结构中编译这段代码,编译它运行良好,但试图执行:Java StudentSolver


I was getting the NoClassDefError.

我得到的是NoClassDefError。


To fix this I simply removed: package valentines;

为了解决这个问题,我简单地去掉了:情人节礼物;


I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.

我不是很精通Java包之类的,但这是我修复错误的方法,如果其他人已经回答了这个问题,我很抱歉,但我不能解释它到我的问题。



My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.

我的解决方案是“利用”缺少的特定类的类路径内容。在我的例子中,我有两个依赖项,虽然我可以使用javac...成功编译,但我不能使用Java...运行结果类文件,因为BouncyCastle JAR中的动态类不能在运行时加载。


javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java

So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got

因此,在编译时和运行时,JVM知道在哪里获取Apache Commons和BouncyCastle依赖项,但是,当运行此代码时,我得到了


Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider

And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.

因此,我按照类路径在相同的位置手动创建了一个名为ext的新文件夹,然后我在其中放置了BouncyCastle JAR,以确保在运行时可以找到它。只要生成的清单指定了JAR的位置,就可以相对于类文件或JAR文件放置JAR。注意:我只需要使用一个包含缺少的类文件的JAR。



Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).

Java无法在运行时找到A类。A类位于Maven项目ArtClient中,来自不同的工作区。因此,我将ArtClient导入到我的Eclipse项目中。我的两个项目使用ArtClient作为依赖项。我将这些库的库引用更改为项目引用(构建路径->配置构建路径)。



And the problem gone away.

这个问题也就消失了。



I had the same problem, and I was stock for many hours.

我有同样的问题,我是股票很多小时。



I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.

我找到了解决方案。在我的例子中,有因此而定义的静态方法。JVM不能创建该类的另一个对象。



For example,

例如,



private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");


I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.

我在从SRC库中删除两个文件后收到此消息,当我将它们带回时,我一直看到此错误消息。



My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

我的解决方案是:重启Eclipse。从那以后,我再也没有看到过这条消息:-)


更多回答

Thanks for mentioning the cause of a NoClassDefFoundError, this helped me a lot! In my case an ExceptionInInitializerError was thrown before, that's how I found out about errors in static blocks.

谢谢你提到NoClassDefFoundError的原因,这对我帮助很大!在我的例子中,以前抛出了ExceptionInInitializerError,这就是我如何发现静态块中的错误的。

@Jared, When I am getting Error: Could not find or load main class, it will be classified under which category of error?

@Jared,当我收到错误:找不到或无法加载主类时,它将被归类为哪一类错误?

@Pops: Made the language more verbose to specify the objects of the verbs "try" :)

@POPS:使语言更加冗长,以指定动词“try”的对象:)

@Vikram the "could not find or load main class" is not a Java exception, it is caused by the launcher (which inspects the JAR and the main manifest attribute).

@Vikram“找不到或加载主类”不是Java异常,它是由启动器(它检查JAR和主清单属性)引起的。

ClassNotFoundException is also thrown when a class has static initialization that throws an error or exception. They probably should have picked a different name for that event.

当类具有引发错误或异常的静态初始化时,也会引发ClassNotFoundException。他们可能应该为这一事件选择一个不同的名字。

I had this error happen when putting a source file under the wrong namespace/package. I figured I could just put it anywhere, and the compiler was happy. Turns out I should have been more diligent for runtime to be happy as well.

我在将源文件放在错误的命名空间/包下时发生了这个错误。我想我可以把它放在任何地方,编译器很高兴。事实证明,我应该更勤奋地运行时才能同样快乐。

I had this error once when my server ran out of memory during a file upload. Every time I tried the upload, I'd get a different error. Eventually it told me I didn't have enough heap space.

有一次,当我的服务器在文件上传过程中内存不足时,我遇到了这个错误。每次我尝试上传时,我都会收到不同的错误。最终,它告诉我没有足够的堆空间。

This answer is not necessarily true and will be misleading to many people! See the better answer from Jared below.

这个答案不一定是真的,而且会误导很多人!请看下面贾里德的更好的答案。

@DaveL. Thanks! Jared's answer with 400+ upvotes is way below! One answer with -4 up(down?)votes is way above it. There is something fishy about SO's answer ordering logic.

@Davel。谢谢!贾里德的回答是400+的好评,远远低于这个数字!一个答案是-4票赞成(反对?),远远高于这个数字。So‘s答案的排序逻辑有些可疑。

This is a long-shot for someone, but I encountered this error because the class in question contained a SimpleDateFormat that was initialized with an invalid character (I had T in the middle instead of 'T').

对于某些人来说,这不太可能,但我遇到了这个错误,因为有问题的类包含一个用无效字符初始化的SimpleDateFormat(我将T放在中间,而不是‘T’)。

And the reason is that after first try jvm already knows its not going to work and throw different exception second time?

原因是在第一次尝试之后,JVM已经知道它不会工作,第二次抛出不同的异常?

@ikamen Apparently it has stored somewhere the unsuccessful class initialisation of SimpleCalculator after the divide by zero? Does someone have a reference to the official documentation for this behaviour?

@ikamen显然,它已经存储在某个地方的SimpleCalculator除以零后不成功的类初始化?有人有这种行为的官方文件吗?

@PhilipRego Not sure what you mean by a 'pure' NoClassDefFoundError. The first time new SimpleCalculator() is called, you get an ExceptionInInitializerError with a caused by of ArithmeticException. The second time you call new SimpleCalculator() you get a NoClassDefFoundError as pure as any other. The point is you can get a NoClassDefFoundError for a reason other than SimpleCalculator.class not being on the classpath at runtime.

@PhilipRego不确定您所说的“纯”NoClassDefFoundError是什么意思。第一次调用new SimpleCalculator()时,您会得到一个ExceptionInInitializerError,其Caused By of ArithmeticException。第二次调用new SimpleCalculator()时,您会得到一个与其他方法一样纯粹的NoClassDefFoundError。关键是,除了SimpleCalculator.class在运行时不在类路径上之外,您可能会因为其他原因而获得NoClassDefFoundError。

Great answer. I think I've tried everything you suggest and still have that problem. I can exclude some of these due to the jar working with spring, but seems to not be liked by java.sql (in my case the sap db driver for Hana).

回答得很好。我想我已经试过你建议的所有方法了,但仍然有这个问题。我可以排除其中的一些,因为JAR与Spring一起工作,但似乎不喜欢java.sql(在我的例子中是用于hana的sap db驱动程序)。

Its actually called System.getproperty("java.class.path")

它实际上名为System.getProperty(“java.class.Path”)

Issue is still not resolved but it is very useful info.

问题仍未解决,但这是非常有用的信息。

Had the same issue. Turns out I compiled the war file with Java7, but my Tomcat installation was using Java6. I had to update my environmental variables

也有同样的问题。原来我是用Java7编译WAR文件的,但我的Tomcat安装使用的是Java6。我不得不更新我的环境变量

If this happens like that then i'll say Java is in a mess. +2 if this is true. Can't verify this yet. If found true will do+1 again (In comments)

如果发生这种情况,那么我会说Java陷入了混乱。如果这是真的,+2。目前还无法证实这一点。如果发现为真,将再次执行+1(在评论中)

This is pretty damn useful piece of advice in real life. I just had the same situation with class attribute initializers. You only have once chance to see the actual problem in the log. Once the class is loaded (or attempted anyway) you need to restart everything.

这是一个非常有用的建议在现实生活中。我刚刚在类属性初始化器上遇到了同样的情况。您只有一次机会在日志中看到实际问题。一旦类被加载(或尝试加载),你需要重新启动一切。

Same thing happened to me when programming a Servlet (NoClassDefFoundError was actually caused by ExceptionInInitalizerError, which was caused by DateTimeParseException). It's a bit misleading, isn't it? I know they probably had their reasons to make it like that, but it would be so nice to have at least a small hint, that NoClassDefFoundError was a result of another exception, without the need to deduce it. Just throwing ExceptionInInitializerError again would be much more clear. Sometimes the connection between the two may not be that obvious.

在编写Servlet时也发生了同样的事情(NoClassDefFoundError实际上是由ExceptionInInitalizerError引起的,而ExceptionInInitalizerError是由DateTimeParseException引起的)。这有点误导,不是吗?我知道他们这样做可能有他们的原因,但如果至少有一个小的提示,NoClassDefFoundError是另一个异常的结果,那就太好了,而不需要推断它。只需再次抛出ExceptionInInitializerError就会清楚得多。有时,两者之间的联系可能并不那么明显。

Link is dead. Try the archived version: web.archive.org/web/20131216000019/https://blogs.oracle.com/…

林克死了。尝试存档版本:web.archive.org/web/20131216000019/https://blogs.oracle.com/…

"EMF"? Do you mean "MEF"?

“EMF”?你是说“MEF”吗?

Nope. EMf as Eclipse Modeling Framework. In automotive we may face this error when running generated code.

不是的。EMF作为Eclipse建模框架。在汽车中,我们在运行生成的代码时可能会遇到此错误。

This is incorrect. A missing resource won't give you this error. You will only get it if a class is missing.

这是不正确的。缺少资源不会给您带来此错误。你只有在缺课的情况下才能拿到它。

@StephenC Maybe I should emphasize that part more, but I wrote for example a properties file that the affected class tries to load from the META-INF directory. This has actually happened to me and I was able to resolve the NoClassDefFoundError by adding the missing properties file. I added this answer exactly because one wouldn’t expect this error under the mentioned circumstances.

@StehenC也许我应该更多地强调这一部分,但我编写了一个属性文件,受影响的类尝试从META-INF目录加载该文件。这实际上发生在我身上,我能够通过添加缺少的属性文件来解决NoClassDefFoundError。我之所以加上这个答案,正是因为在上述情况下,人们不会预料到这个错误。

You have missed something very important in your explanation then, because the only way that a missing resource file could trigger that exception is if you are attempting to load the resource file in a static initialization ... which triggered an unchecked exception and caused the class init to fail. Any unchecked exception propagating from static initialization would do that.

那么,您在解释中遗漏了一些非常重要的东西,因为丢失的资源文件可能触发该异常的唯一方式是尝试在静态初始化中加载资源文件...这触发了一个未检查的异常并导致类init失败。任何从静态初始化传播的未检查异常都会这样做。

If I am wrong (i.e. this is not due to failed static initialization), I would be interested to see an actual example (i.e. an MCVE) that demonstrates the behavior.

如果我错了(即这不是由于静态初始化失败),我将有兴趣看到一个演示该行为的实际示例(即MCVE)。

@StephenC You’re absolutely right, though :( I looked up the case where I encountered this issue and it indeed involved a static initializer trying to load a resource bundle. I shall augment/correct my description of the cause. Thanks for pointing this out.

@StehenC你是绝对正确的,不过:(我查了一下我遇到这个问题的案例,它确实涉及一个试图加载资源包的静态初始化器。我将补充[更正]我对原因的描述。谢谢你指出这一点。

That's explained by the most voted answer, when you first compiled, the files were there, then you removed some files, the classes were deleted, so at runtime, you got the ClassNotFound, then you broght them back, but still Eclipse didn't notice so the generated classes were still missing, but after you restarted Eclipse, the workspace was refreshed and the classes were again available, but in general this is not a solution or workaround, the solution is finding which class/jar is missing in the runtime classpath.

投票最多的答案解释了这一点,当您第一次编译时,文件在那里,然后您删除了一些文件,类被删除,所以在运行时,您获得了ClassNotFound,然后将它们取回,但是仍然没有注意到生成的类仍然丢失,但是在您重新启动Eclipse后,工作区被刷新,类再次可用,但总的来说,这不是解决方案或变通方法,解决方案是查找运行时类路径中缺少的类/JAR。

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com