mercredi 17 juin 2015

Instantiate type-parametrized class at runtime with default constructor

I want to instantiate a new object with the following classes:

class Test[T : ClassTag](val value : T) extends Serializable

private object Test {
  private var testClass : Class[_] = _

  def setTestClass(test : Class[_]) : Unit = {
    testClass = test
  }

  def apply[T : ClassTag](value : T) : Test[T] = {
    testClass.getConstructors()(0).newInstance(value).asInstanceOf[Test[T]]
  }
}

class Subtest[T : ClassTag](
    override val value : T, 
    val additional : Integer
) extends Test[T](value)

I set the test-class with setTestClass somewhere, that has been loaded with Class.forName from a string. Let say it is "Subtest". I wish to instantiate a new Subtest[String] with - for example the following code:

Test("my random string") // It should return a new Subtest[String]

The problem is that newInstance throws java.lang.IllegalArgumentException: wrong number of arguments. I've checked the parameterTypes of the Constructor, and there are two parameter types:

  • class java.lang.Object
  • interface scala.reflect.ClassTag

Okay. How to supply the ClassTag? What is the problem here? Is there a better approach, workaround for this?





Aucun commentaire:

Enregistrer un commentaire