【问题标题】:Get a TypeTag from a Type?从类型中获取 TypeTag?
【发布时间】:2015-01-12 05:18:52
【问题描述】:

我可以使用tpe 方法从TypeTag[A] 获得Type。但是我也可以从类型中恢复类型标签吗?

import scala.reflect.runtime.{universe => ru}
import ru.{Type, TypeTag}

def forward[A](implicit tt: TypeTag[A]): Type = tt.tpe

def backward(t: Type): TypeTag[_] = ???

原因是我有一个使用类型标签作为映射键的 API,但在某些时候我只有类型并删除了标签。

【问题讨论】:

标签: scala reflection


【解决方案1】:

有可能:

import scala.reflect.runtime.universe._
import scala.reflect.api

val mirror = runtimeMirror(getClass.getClassLoader)  // whatever mirror you use to obtain the `Type`

def backward[T](tpe: Type): TypeTag[T] =
  TypeTag(mirror, new api.TypeCreator {
    def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
      if (m eq mirror) tpe.asInstanceOf[U # Type]
      else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
  })

assert(backward[String](forward[String]) == typeTag[String])

【讨论】:

  • TypeCreatorapiUniverse 来自哪里?
  • 注意。此方法可防止 TypeTag 被序列化。抛出:java.io.NotSerializableException: scala.reflect.runtime.JavaMirrors$JavaMirror 编译器生成的 typetag 似乎是可序列化的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2020-06-28
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
相关资源
最近更新 更多