scalareflectionscala.js

Generic way of array creation in Scala.js


I'm looking for a generic way of array creation in Scala.js.

The following code works fine in JVM and Scala Native platforms:

def newArray[A](fqcn: String, size: Int): Array[A] = {
  val clazz = Class.forName(fqcn)
  java.lang.reflect.Array.newInstance(clazz, size).asInstanceOf[Array[A]]
}

But in Scala.js I cannot find an ability to create an instance of java.lang.Class.

I've tried such replacement for Class.forName but it doesn't work for arbitrary classes:

val clazz = scala.scalajs.reflect.Reflect.lookupInstantiatableClass(fqcn)
  .getOrElse(throw new ClassNotFoundException(fqcn))
  .runtimeClass

Solution

  • You cannot get a java.lang.Class from a string. There's the reflection API, as you noticed, but that is only for very specific classes that have been annotated with @EnableReflectiveInstantiation. This is usually only used by test framework classes.

    The Scala way would be to take an implicit ClassTag[A], which is the defining purpose of ClassTag. An alternative is to pass the java.lang.Class as argument, and at call site, give it as a classOf[C] for a concrete C.

    From a string, it's not possible.