为什么 TypeTag 没有方法 runtimeClass 但 Manifest 和 ClassTag 有 [英] Why TypeTag doesnt have method runtimeClass but Manifest and ClassTag do

查看:41
本文介绍了为什么 TypeTag 没有方法 runtimeClass 但 Manifest 和 ClassTag 有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以将String一般地转换为Dto,如果我使用Manifest和ClassTag,我可以使用方法runtimeClass来获取运行时类,但TypeTag没有这个方法

I have this code to generically transform String to Dto, if I am using Manifest and ClassTag, both of it I can use method runtimeClass to get runtime class, but TypeTag doesnt have this method

class ObjectMapper[T] {

  def readValue(x: String, t: Class[T]): T = ???
}

class Reader {
  def read[W: Manifest](x: String): W = {
    val mapper = new ObjectMapper[W]
    mapper.readValue(x, implicitly[Manifest[W]].runtimeClass.asInstanceOf[Class[W]])
  }

}

我可以知道为什么 TypeTag 没有方法 runtimeClass

May I know why TypeTag doesnt have method runtimeClass

非常感谢

推荐答案

假设 TypeTag 来自 scala.reflect.runtime.universe,你可以得到这样的类这个:

Assuming the TypeTag comes from scala.reflect.runtime.universe, you can get the class like this:

def runtimeClass(tag: TypeTag) = tag.mirror.runtimeClass(tag.tpe)

它没有这个方法,因为并非所有的 TypeTag 都来自运行时宇宙.

It doesn't have this method because not all TypeTags are from the runtime universe.

这篇关于为什么 TypeTag 没有方法 runtimeClass 但 Manifest 和 ClassTag 有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆