您只需致电template.getClass
即可获得template
课程。它要求template
是的AnyRef
一个亚型,所以无论你将它转换为AnyRef
(迫使原始类型的拳击)或您添加的上限为T
:
def instantiateItem[I, T <: AnyRef](implicit mf: Manifest[I], template: T): I = {
val constructor = mf.erasure.getConstructor(template.getClass)
constructor.newInstance(template).asInstanceOf[I]
}
如果你想在template
传递明确,作为由你的问题中的代码表示,你需要分离隐式和显式参数,例如
def instantiateItem[I, T <: AnyRef](template: T)(implicit mf: Manifest[I]): I = {
val constructor = mf.erasure.getConstructor(template.getClass)
constructor.newInstance(template).asInstanceOf[I]
}
又名
def instantiateItem[I : Manifest, T <: AnyRef](template: T): I = {
val mf = implicitly[Manifest[I]]
val constructor = mf.erasure.getConstructor(template.getClass)
constructor.newInstance(template).asInstanceOf[I]
}
一般来说如果可能的话,你可能会避免在所有使用反射与精心的设计:
trait ItemCompanion[I,T] {
def instantiateItem(template: T): I
}
object TestItem extends ItemCompanion[TestItem, TestTemplate] {
implicit def self: ItemCompanion[TestItem, TestTemplate] = this
def instantiateItem(template: TestTemplate): TestItem = new TestItem(template)
}
class TestItem(template: TestTemplate)
trait TestTemplate
// try out
def instantiateItem[I, T](implicit ic: ItemCompanion[I, T], t: T): I =
ic.instantiateItem(t)
implicit val temp: TestTemplate = new TestTemplate {}
instantiateItem[TestItem, TestTemplate]
这将编译被弃用,但我有一个问题,称它: 没有足够的论据方法instantiateItem:(隐式MF:舱单[I],隐模板:T)我。未指定的值参数模板。 – hezamu 2012-08-11 15:57:23
你的通话看起来如何?它应该是'instantiateItem [TestItem,TestTemplate]' – 2012-08-11 16:05:48
在你的问题中你明确地传递了'template'参数。然后你必须传入_both_参数(首先是清单,然后是模板)。如果你想要_that_,你应该用两个参数列表来定义方法,例如'def instantiateItem [I,T <:AnyRef](template:T)(implicit mf:Manifest [I]):I' – 2012-08-11 16:08:37