Scala:在没有运行时反射且没有类型实例的情况下获取类型名称 [英] Scala: Get type name without runtime reflection and without type instance

查看:156
本文介绍了Scala:在没有运行时反射且没有类型实例的情况下获取类型名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一种类型的名称(如String),而无需运行时反射.

I'd like to get the name of a type, as a String, without runtime reflection.

使用宏,并使用该类型的实例,我可以这样做:

Using macros, and with an instance of the type, I can do it like this:

def typeNameFromInstance[A](instance: A): String = 
  macro typeNameFromInstanceImplementation[A]

def typeNameFromInstanceImplementation[A](
  c: Context)(
    instance: c.Expr[A]): c.Expr[String] = {
  import c.universe._

  val name = instance.actualType.toString
  c.Expr[String](Literal(Constant(name)))
}

在没有该类型实例的情况下如何做到这一点?我想要一个函数签名,例如:

How can I do this without an instance of the type? I'd like a function signature like:

def typeName[A]: String

我不能使用ClassTags,因为它们不提供完整的类型名称,而仅提供已擦除的类型.由于线程安全问题,我显然也不能使用TypeTag.

I can't use ClassTags because they don't provide the full type name, just the erased type. I also apparently can't use TypeTags because of thread safety issues.

看来这不可能完全通用(例如,嵌套函数调用).下面接受的答案在评论中对此进行了说明.

It appears this isn't possible in full generality (eg nested function calls). The accepted answer below states this in the comments.

推荐答案

您可以访问表示宏应用程序的树:c.macroApplication

You can access tree that represents macro application: c.macroApplication

def typeName[T]: String = macro typeName_impl[T]

def typeName_impl[T](c: Context): c.Expr[String] = {
  import c.universe._

  val TypeApply(_, List(typeTree)) = c.macroApplication
  c.literal(typeTree.toString())
}

获得相同结果的另一种方法,但可能会更好一些:

Another way to get the same, but maybe a little nicer:

def typeName[T]: String = macro typeName_impl[T]

def typeName_impl[T: c.WeakTypeTag](c: Context): c.Expr[String] = {
  import c.universe._

  c.literal(weakTypeOf[T].toString())
}

这篇关于Scala:在没有运行时反射且没有类型实例的情况下获取类型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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