development

java.lang.NoClassDefFoundError : 클래스 XXX를 초기화 할 수 없습니다

big-blog 2020. 6. 13. 09:28
반응형

java.lang.NoClassDefFoundError : 클래스 XXX를 초기화 할 수 없습니다


public class PropHolder {
  public static Properties prop;

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

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

class PropHolder내 자신의 클래스입니다. 클래스는 기본 클래스와 동일한 JAR 파일에 있습니다. 따라서 클래스 경로에서 JAR이 누락되어서는 안됩니다.

로 JAR 파일을 살펴보면 나열된 파일을 jar tf myjarfile볼 수 있습니다 PropHolder.class.

Btw : 코드가 로컬 컴퓨터에서 제대로 실행되고 있습니다. 그러나 일부 스크립트를 사용하여 Linux 서버에 배포하면 작동하지 않았습니다. 따라서 코드의 문제가 아니라고 생각합니다. 그러나 어떤 이유로 든. 배포 프로세스는 추적하기가 매우 어렵습니다.

무엇이 문제 일 수 있습니까?


최선의 방법은 여기에 문제가 있다는 것입니다.

static {
    //code for loading properties from file
}

잡히지 않은 예외가 발생하여 클래스를로드하려고 시도하는 실제 ClassLoader까지 전파 된 것처럼 보입니다. 그래도이를 확인하려면 스택 추적이 필요합니다.

PropHolder.prop정적 변수를 만들 때 또는 발생했습니다 .


당신은 java.lang.NoClassDefFoundError클래스가 누락되었다는 것을 의미하지는 않습니다 (이 경우에는을 얻습니다 java.lang.ClassNotFoundException). 클래스를 읽으려고 할 때 클래스 정의를 읽는 중에 클래스 로더에 오류가 발생했습니다.

정적 이니셜 라이저 안에 try / catch를 넣고 예외를 살펴보십시오. 일부 파일을 읽고 로컬 환경과 다른 경우 문제의 원인 일 가능성이 높습니다 (파일을 찾을 수 없거나 권한이없는 것일 수 있음).


NoClassDefFoundError는 정적 블록 내부에서 무엇이 잘못되었는지에 대한 단서를 제공하지 않습니다. 정적 {...} 초기화 코드 안에 항상 이와 같은 블록을 두는 것이 좋습니다.

static {
  try {

    ... your init code here

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

나는 같은 예외가 있었는데, 이것이 내가 문제를 해결 한 방법입니다.

전제 조건 :

  1. 다른 클래스를 확장 한 Junit 클래스 (및 테스트)

  2. ApplicationContext는 프로젝트를 초기화하는 스프링을 사용하여 초기화되었습니다.

  3. @Before 메소드에서 애플리케이션 컨텍스트가 초기화되었습니다.

해결책:

부모 클래스에도 응용 프로그램 컨텍스트 내에서 초기화 된 일부 클래스가 필요했기 때문에 @BeforeClass 메서드에서 응용 프로그램 컨텍스트를 초기화하십시오.

이것이 도움이되기를 바랍니다.


위에서 언급했듯이 이것은 여러 가지 일 수 있습니다. 제 경우에는 속성 파일에서 누락 된 항목에 의존하는 정적으로 초기화 된 변수가있었습니다. 특성 파일에 누락 된 항목을 추가하면 문제점이 해결되었습니다.


동일한 예외가 있었지만 디버그 모드로 실행하는 동안에 만 3 일 동안 문제를 해결하는 방법입니다. build.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 

에:

public class MyAppClass  extends MultiDexApplication 

this solved it. hope this will help someone


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 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

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

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.


If you're working on an Android project, make sure you aren't calling any static methods on any Android classes. I'm only using JUnit + Mockito, so maybe some other frameworks might help you avoid the problem altogether, I'm not sure.

My problem was calling Uri.parse(uriString) as part of a static initializer for a unit test. The Uri class is an Android API, which is why the unit test build couldn't find it. I changed this value to null instead and everything went back to normal.


I had the same problems:java.lang.NoClassDefFoundError: Could not initialize class com.xxx.HttpUtils

static {
    //code for loading properties from file
}

it is the environment problem.That means the properties in application.yml is incorrect or empty!

참고URL : https://stackoverflow.com/questions/7325579/java-lang-noclassdeffounderror-could-not-initialize-class-xxx

반응형