是否可以将 TypeTag 转换为 Manifest? [英] Is it possible to convert a TypeTag to a Manifest?

查看:40
本文介绍了是否可以将 TypeTag 转换为 Manifest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的库使用 TypeTags,但现在我们需要与另一个需要 Manifests 的库进行交互.有没有什么简单的方法可以从 TypeTag 创建一个 Manifest?

Our library uses TypeTags, but now we need to interact with another library which requires Manifests. Is there any simple way to create a Manifest from a TypeTag?

推荐答案

gourlaysama 的答案使用 Class[_],因此类型参数被删除.我想出了一个在这里保留类型参数的实现:TypeTag 到 Manifest 的转换过程中如何维护类型参数?

gourlaysama's anwer uses Class[_], thus type arguments are being erased. I've come up with an implementation that preserves the type arguments here: How to maintain type parameter during TypeTag to Manifest conversion?

代码如下:

  def toManifest[T:TypeTag]: Manifest[T] = {
    val t = typeTag[T]
    val mirror = t.mirror
    def toManifestRec(t: Type): Manifest[_] = {
      val clazz = ClassTag[T](mirror.runtimeClass(t)).runtimeClass
      if (t.typeArgs.length == 1) {
        val arg = toManifestRec(t.typeArgs.head)
        ManifestFactory.classType(clazz, arg)
      } else if (t.typeArgs.length > 1) {
        val args = t.typeArgs.map(x => toManifestRec(x))
        ManifestFactory.classType(clazz, args.head, args.tail: _*)
      } else {
        ManifestFactory.classType(clazz)
      }
    }
    toManifestRec(t.tpe).asInstanceOf[Manifest[T]]
  }

这篇关于是否可以将 TypeTag 转换为 Manifest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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