无法指定 ClassTag 时在运行时获取 class 信息
Getting at runtime class information when you cannot specify ClassTag
在编写测试以验证是否在内部某处选择了正确的类型类时,我 运行 进入了 type erasure。我没有将 ClassTag
添加到签名的选项,除非我也污染了特征的非测试版本,因为添加 : ClassTag
会更改方法签名,使其不再是覆盖,例如:
trait Foo {
def bar[T: MyTypeClass](t: T): Unit
}
class FooStubImpl extends Foo {
override def bar[T: MyTypeClass: ClassTag](t: T): Unit = {
val ct = classTag[T]
}
}
这会导致以下编译错误:
Error:(12, 20) method bar overrides nothing
Note: the super classes of class FooStubImpl contain the following, non final member named bar:
override def bar[T](t: T)(implicit evidence: MyTypeClass[T]): Unit = {
^
是否有另一种方法可以在 运行 时获取不需要 ClassTag
的参数化类型的类型信息?
如果您有相关类型的运行时值,只需检查该类型即可。 Class-只有在您没有价值证据时才需要标签。
class FooStubImpl extends Foo {
override def bar[T: MyTypeClass](t: T): Unit = {
val clazz = t.getClass
}
}
在编写测试以验证是否在内部某处选择了正确的类型类时,我 运行 进入了 type erasure。我没有将 ClassTag
添加到签名的选项,除非我也污染了特征的非测试版本,因为添加 : ClassTag
会更改方法签名,使其不再是覆盖,例如:
trait Foo {
def bar[T: MyTypeClass](t: T): Unit
}
class FooStubImpl extends Foo {
override def bar[T: MyTypeClass: ClassTag](t: T): Unit = {
val ct = classTag[T]
}
}
这会导致以下编译错误:
Error:(12, 20) method bar overrides nothing Note: the super classes of class FooStubImpl contain the following, non final member named bar:
override def bar[T](t: T)(implicit evidence: MyTypeClass[T]): Unit = { ^
是否有另一种方法可以在 运行 时获取不需要 ClassTag
的参数化类型的类型信息?
如果您有相关类型的运行时值,只需检查该类型即可。 Class-只有在您没有价值证据时才需要标签。
class FooStubImpl extends Foo {
override def bar[T: MyTypeClass](t: T): Unit = {
val clazz = t.getClass
}
}