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服务器上时就无法工作了。所以我认为这不是代码的问题。 但出于某种原因。部署过程很难跟踪。

有什么问题吗?


当前回答

如果你正在开发一个Android项目,确保你没有在任何Android类上调用任何静态方法。我只使用JUnit + Mockito,所以也许一些其他框架可以帮助您避免这个问题,我不确定。

我的问题是调用Uri.parse(uriString)作为单元测试的静态初始化器的一部分。Uri类是一个Android API,这就是单元测试构建找不到它的原因。我把这个值改为null,一切恢复正常。

其他回答

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

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

如果你正在开发一个Android项目,确保你没有在任何Android类上调用任何静态方法。我只使用JUnit + Mockito,所以也许一些其他框架可以帮助您避免这个问题,我不确定。

我的问题是调用Uri.parse(uriString)作为单元测试的静态初始化器的一部分。Uri类是一个Android API,这就是单元测试构建找不到它的原因。我把这个值改为null,一切恢复正常。

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