Dynamically creating a new instance of the case class in scala

Given a reference to a companion class object tand a sequence of parameters seq, how can I call a new instance of the case class?

I can create a class when I dial the parameter number myself.

scala> case class B(n:String,a:Int,b:Int)
defined class B

scala> val t:AnyRef = B
t: AnyRef = B

scala> val m = t.getClass.getMethods.filter{m => m.getName == "apply"}.
    filterNot {_.getReturnType.getName == "java.lang.Object"}(0)
m: java.lang.reflect.Method = public B B$.apply(java.lang.String,int,int)

scala> m.invoke(t,"name",1:java.lang.Integer,2:java.lang.Integer)
res99: Object = B(name,1,2)

The problem that I could not solve was to call a call with a sequence of arguments such as Seq("name",1:java.lang.Integer,2:java.lang.Integer). Any help on how to do this is greatly appreciated.

I am using scala 2.10.0.

+5
source share
1 answer

I just found it myself (respectively, looked here fooobar.com/questions/362957 / ... ). it

method.invoke(t,seq: _*)

Sometimes it really helps just write it down; -)

+4
source

All Articles