samedi 11 avril 2015

Scala reflection and generics

I am facing an issue with Scala reflection and generics. I have an abstract class which has this signature:



IPartition [T <: IPartition[T]] (val bounds: Array[BoundsInOneDimension],
val boxId: BoxId = 0, val partitionId: Int = -1, var adjacentPartitions: List[T] = Nil)


and a concrete class with this signature:



Box (bounds: Array[BoundsInOneDimension], boxId: BoxId = 0, partitionId: Int = -1, adjacentBoxes: List[Box] = Nil)
extends IPartition[Box] (bounds, boxId, partitionId, adjacentBoxes)


What I wanna do is to instantiate the concrete class within a generic method of an object. Thus, I have this method:



myMethod[SHAPE <: IPartition[SHAPE]] (...) (implicit m:Manifest[SHAPE]): Iterable[SHAPE]


and in this method I need to instantiate the generic class SHAPE extending the abstract class above.


By now, I have tried doing this:



m.getClass.getConstructors.apply(0).newInstance(combinations(i).reverse , Int.box(i+1), Int.box(-1)).asInstanceOf[SHAPE]


But I get a java.lang.IllegalArgumentException. Then I printed the parameter expected by the constructor which are:



class scala.Option
class java.lang.Class
class scala.collection.immutable.List


And I can't understand this. I expected 4 parameters, or 1, or something similar. Moreover, I didn't expected a scala.Option as first parameter, neither a java.lang.Class as second.


I can't understand what to do to correctly instantiating the class I need with the proper parameters. May anyone help me?


Thanks. Marco






Aucun commentaire:

Enregistrer un commentaire