Search code examples
javajava.lang.class

Class.forName + ExceptionInInitializerError + static initialization + weird Array init


I recently "inherited" a project and tried to get an instance of a service running locally. I encountered - and fixed - some problems with code similar to...

class A {
   // ...
   public void doSomething() {
      // ...
      Class foo = Class.forName("fully.qualified.package.B"); 
      // ...  
   }
   // ...
}

class B {
    static String[] bar = (String[])Arrays.asList("Something").toArray();
    //...
}

When Class A.doSomething() was run, an ExceptionInInitializerError was thrown. This error has something to do with initializing Class B (static init, no instantiation!!).

FYI > Fixing this Problem can be done in two ways...

  • Class A, use Class.forName("fully.qualified.package.B", false, this.getClass().getRuntime()); - where the second parameter false does not initialize the class.
  • Class B, using a normal array init static String[] bar = { "Something" };.

What I am interested in is...

Why would the somewhat overengineered initialization via (String[]) Arrays.asList(...).toArray() cause such an error?


Solution/Edit: It has nothing to do with static initialization, the array init is plain wrong, see below...


Solution

  • (String[])Arrays.asList("Something").toArray(); is going to fail at runtime: it's not returning a String[], it's returning an Object[]. Object[] and String[] are reifiable types, so it's a checked cast, and because an Object[] is not a String[], it fails.

    Use Arrays.asList("Something").toArray(new String[0]); or just new String[]{"Something"}.