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 parameterfalsedoes 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...
(String[])Arrays.asList("Something").toArray();is going to fail at runtime: it's not returning aString[], it's returning anObject[].Object[]andString[]are reifiable types, so it's a checked cast, and because anObject[]is not aString[], it fails.Use
Arrays.asList("Something").toArray(new String[0]); or justnew String[]{"Something"}.