Java static inner class initialization errors

Context: The java.io.File class has a static inner class method as follows:

LazyInitialization.temporaryDirectory(); 

[EDITED added a few more codes] My code below ultimately calls the above line of code. The exception is thrown from the timeDirectory () method, which in my context is accurate / expected.

 try { File tempFile = File.createTempFile("aaa", "aaa"); } catch (Exception e) { // handle exception } 

Then, when I call the same method again (createTempFile), I get a "java.lang.NoClassDefFound error". Failed to initialize class java.io.File $ LazyInitialization "

Question: I suggested that the inner LazyInitialization class should be loaded by the class loader when its static method was called, although the inner method threw an exception. However, why do I see a NoClassDefFound error when called a second time? Wrong initial assumption?

+4
source share
1 answer

When a static initialization code throws an exception at runtime, it wraps an ExceptionInInitializerError and is called in the context of the code that starts loading the class (if it is an Error exception, it is not wrapped). At this point, the class did not load. Therefore, any attempt to use it later will raise a NoClassDefFoundError.

Perhaps this is what you are experiencing.

+7
source

All Articles