【发布时间】:2013-09-24 13:50:47
【问题描述】:
我有一个具有以下签名的函数:
myFunc[T <: AnyRef](arg: T)(implicit m: Manifest[T]) = ???
如果我在编译时不知道参数的确切类型,如何调用此函数?
例如:
val obj: AnyRef = new Foo() // At compile time obj is defined as AnyRef,
val objClass = obj.getClass // At runtime I can figure out that it is actually Foo
// Now I would need to call `myFunc[Foo](obj.asInstanceOf[Foo])`,
// but how would I do it without putting [Foo] in the square braces?
我想写一些逻辑上类似的东西:
myFunc[objClass](obj.asInstanceOf[objClass])
谢谢!
更新:
问题无效 - 正如@DaoWen、@Jelmo 和@itsbruce 正确指出的那样,我试图做的事情完全是一派胡言!我只是严重地考虑了这个问题。 谢谢你们!太糟糕了,我不能接受所有的答案都是正确的:)
所以,问题是由以下情况引起的:
我正在使用Salat 库将对象序列化到/从 BSON/JSON 表示。
Salat 有一个 Grater[T] 类,用于序列化和反序列化。
BSON 对 反序列化 的方法调用如下所示:
val foo = grater[Foo].asObject(bson)
到这里,类型参数的作用就很明确了。我当时想做的是使用相同的 Grater 来序列化我的域模型中的任何实体。于是我写了:
val json = grater[???].toCompactJSON(obj)
我立即急忙进行反思,只是没有看到表面上有明显的解决方案。即:
grater[Entity].toCompactJSON(obj) // where Entity...
@Salat trait Entity // is a root of the domain model hierarchy
有时事情比我们想象的要容易得多! :)
【问题讨论】:
标签: scala reflection types implicit