简体   繁体   English

动态在scala中创建案例类的新实例

[英]dynamical creating a new instance of a case class in scala

Given a reference to a case class companion object t and a sequence of parameter seq how can I invoke a new instance of the case class? 给定对case类伴随对象t的引用和参数seq的序列如何调用case类的新实例?

I can create a class when I type the number of the parameter by 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 I couldn't solve is to call invoke with a sequence of arguments like Seq("name",1:java.lang.Integer,2:java.lang.Integer) . 我无法解决的问题是使用一系列参数调用invoke,如Seq("name",1:java.lang.Integer,2:java.lang.Integer) Any help how to do that is greatly appreciated. 任何帮助如何做到这一点非常感谢。

I use scala 2.10.0. 我使用scala 2.10.0。

Just found it out by myself (respectively have seen it over here https://stackoverflow.com/a/2060503/55070 ). 只是自己找到它(分别在这里看到它https://stackoverflow.com/a/2060503/55070 )。 It's 它的

method.invoke(t,seq: _*)

Sometimes it really helps to just write it down ;-) 有时候把它写下来确实很有帮助;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM