scala - How do I reflectively create a new collection? -
i have instance of collection want store externally , restore original collection type. example
class foo { var x : list[int] } val f = new foo f.x = list(1, 2, 3)
i "serialize" out f, want reflectively create new foo, f2, , populate f2.x correct results.
i can create new foo doing classof[foo].newinstance
, how create correct collection type , populate it?
note, i'm making lots of assumptions here, notable: 1) know type of f.x, , can serialize out type of 2) i'm serializing out contents of x preserves values 3) don't want use "standard" serialization
i've tried use builders available on original collection, don't quite understand how works enough pull off.
thanks,
dave
it easier here if had better idea of problem you're trying solve, e.g. why don't want use standard object serialization.
that said, if want reflection on scala collection classes, you'll need know few things how scala compiles classes , objects:
if want class list object (not list class), name
scala.collection.immutable.list$
- note final dollar sign.if want singleton list object instance, that's stored field
module$
.most scala collection companion objects provide
newbuilder
method creates object has+=
($plus$eq
) method ,result
method allow create new collection.
so like:
scala> def buildbyreflection[t](collectionclassname: string, items: array[t]) = { | val companionclass = class.forname(collectionclassname + "$") | val companion = companionclass.getfield("module$").get(null) | val newbuilder = companionclass.getmethod("newbuilder") | val builder = newbuilder.invoke(companion) | val pluseq = builder.getclass.getmethod("$plus$eq", classof[object]) | (item <- items) { | pluseq.invoke(builder, item.asinstanceof[anyref]) | } | builder.getclass.getmethod("result").invoke(builder) | } buildbyreflection: [t](collectionclassname: string,items: array[t])java.lang.object scala> buildbyreflection("scala.collection.immutable.list", array(1, 2, 3)) res0: java.lang.object = list(1, 2, 3)
Comments
Post a Comment