dimanche 23 octobre 2016

Scala: create instance from generic type with private constructor

I have a class with a generic type parameter and I would like to create an instance of this type using reflection. Moreover, the type has a private constructor. Here is a code sample of the problem:

class X private (x: Int) {
}
class Y private (y: Int) {
}
abstract class Foo[T](z : Int) {
  var bar : T = createInstance[T](z)
  def createInstance[T](z: Int) : M = {
     ???
  }
}

This would allow me to instantiate Foo and access bar:

class xFoo extends Foo[X]{
}

class yFoo extends Foo[Y]{
}

var xfoo = new xFoo(5)
println(xfoo.bar.x)

var yfoo = new yFoo(6)
println(yfoo.bar.y)

This should print out '5' and '6'.

I have tried using implicit in the following way.

def createInstance[T](z: Int)(implicit tag: TypeTag[T]) : T = {
  val clazz = tag.tpe.getClass
  val ctor = class.getDeclaredConstructor(classOf[Int])
  ctor.setAccessible(true)
  return ctor.newInstance(z).asInstanceOf[T]
}

However, then I get the error:

No TypeTag available for T

in line

var bar : T = createInstance[T](z)

Any suggestions? Thanks for your help!





Aucun commentaire:

Enregistrer un commentaire