Scala defensive coding around asInstanceOf coercion

109 Views Asked by At

A case in point:

java.lang.ExceptionInInitializerError
    at sun.misc.Unsafe.ensureClassInitialized(Native Method)
    at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
    at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:142)
    at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
    at java.lang.reflect.Field.get(Field.java:393)
    at utest.runner.BaseRunner.runUTestTask(BaseRunner.scala:30)
    at utest.runner.BaseRunner$$anonfun$utest$runner$BaseRunner$$makeTask$1.apply(BaseRunner.scala:95)
    at utest.runner.BaseRunner$$anonfun$utest$runner$BaseRunner$$makeTask$1.apply(BaseRunner.scala:95)
    at utest.runner.Task.executeInternal(Task.scala:48)
    at utest.runner.Task.execute(Task.scala:19)
    at sbt.TestRunner.runTest$1(TestFramework.scala:76)
    at sbt.TestRunner.run(TestFramework.scala:85)
    at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
    at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
    at sbt.TestFramework$.sbt$TestFramework$$withContextLoader(TestFramework.scala:185)
    at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
    at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
    at sbt.TestFunction.apply(TestFramework.scala:207)

Here is the source location that bumps into that exception and here is a copy of the line:

val suite = TestUtils.loadModule(name, testClassLoader).asInstanceOf[TestSuite]

I'll be debugging utest tomorrow to trace this particular case, which must be an edge case as it happens only in one of my utest-enabled projects (Probably related to directory paths and package alignments there).

But can you suggest a good form of defensive programming avoiding this kind of reflection error, such that the code can catch the error condition before the call to asInstanceOf, or, alternatively, idiomatic code for a catch block - conveying the reasons for the coercion failure, in a more actionable manner?

0

There are 0 best solutions below