public class PropHolder {
  public static Properties prop;

  static {
    //code for loading properties from file
  }
}

// Referencing the class somewhere else:
Properties prop = PropHolder.prop;

propolder是我自己的一个类。类驻留在主类的同一个JAR文件中。所以这不应该,因为类路径中缺少任何JAR。

当我通过JAR tf myjarfile查看JAR文件时,我可以看到propolder .class列在那里。

顺便说一句:代码在我的本地机器上运行良好。但是当我将它与一些脚本一起部署到Linux服务器上时就无法工作了。所以我认为这不是代码的问题。 但出于某种原因。部署过程很难跟踪。

有什么问题吗?


当前回答

我认为这里有个问题:

static {
    //code for loading properties from file
}

它会出现一些未捕获的异常,并传播到实际的ClassLoader,试图加载该类。不过,我们需要一个堆栈跟踪来确认这一点。

要么是这样,要么是在创建propolder时发生的。道具静态变量。

其他回答

我有同样的异常-但只是在调试模式下运行, 这就是我解决问题的方法(在3天之后): 在构建中。Gradle我有: “multiDexEnabled true”设置在defaultConfig部分。

        defaultConfig {
    applicationId "com.xxx.yyy"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 5123
    versionName "5123"
    // Enabling multidex support.
    multiDexEnabled true
}

但显然这还不够。 但当我改变了:

public class MyAppClass  extends Application 

to:

public class MyAppClass  extends MultiDexApplication 

这就解决了问题。 希望这能帮助到一些人

如上所述,这可能是许多事情。在我的情况下,我有一个静态初始化的变量,它依赖于我的属性文件中缺少的条目。将缺失的条目添加到属性文件中,问题就解决了。

NoClassDefFoundError没有提供关于静态块内部发生了什么错误的太多线索。在static{…中总是有这样一个块是很好的实践。}初始化代码:

static {
  try {

    ... your init code here

  } catch (Throwable t) {
    LOG.error("Failure during static initialization", t);
    throw t;
  }
}

我认为这里有个问题:

static {
    //code for loading properties from file
}

它会出现一些未捕获的异常,并传播到实际的ClassLoader,试图加载该类。不过,我们需要一个堆栈跟踪来确认这一点。

要么是这样,要么是在创建propolder时发生的。道具静态变量。

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

为了运行一个任务,因为我的静态变量是要启动一个容器(或者可能初始化一个新的类加载器),所以它将一直保持到JVM停止,而JVM只有在一个进程中的所有任务停止时才会停止。每个任务都会启动一个新的容器(或类加载器),这会让jvm感到困惑。结果,错误发生了。 那么,如何解决呢?我的解决方案是向maven命令添加一个新命令,并使每个任务都转到相同的容器中。

-Dxxx.version=xxxxx #sorry can't post more

也许你已经解决了这个问题,但仍然希望它能帮助其他遇到同样问题的人。