我有一个具有以下签名的函数:
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])
谢谢你!
UPDATE:
这个问题是无效的 - 正如@DaoWen、@Jelmo 和@itsbruce 正确指出的那样,我想做的事情完全是无稽之谈!我只是认真地思考了这个问题。
感谢你们!太糟糕了,我不能接受所有正确的答案:)
所以,这个问题是由以下情况引起的:
我在用Salat https://github.com/novus/salat用于将对象序列化为 BSON/JSON 表示形式或从 BSON/JSON 表示形式序列化的库。Salat
has an Grater[T]
用于序列化和反序列化的类。
该方法调用了反序列化来自 BSON 看起来是这样的:
val foo = grater[Foo].asObject(bson)
到这里,类型参数的作用就清楚了。我当时想做的是使用同一个刨丝器连载我的域模型中的任何实体。所以我写道:
val json = grater[???].toCompactJSON(obj)
我立即进行反思,但表面上并没有看到明显的解决方案。这是:
grater[Entity].toCompactJSON(obj) // where Entity...
@Salat trait Entity // is a root of the domain model hierarchy
有时候事情比我们想象的要容易得多! :)