0

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...

1 Answers1

4

(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"}.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • You are right, didn't occur to me to question the cast, focussed only on the static init. Project is live and running and I assumed this would work. As written in my question, FYA - initializing the array via `{"..."}` solves the problem. Thanks for opening my eyes :-) – seventy2eleven May 17 '21 at 13:58