有几种方法:
1) 运行时。由于擦除,JVM 会丢失有关多态类型(泛型)的信息,但是如果您需要对对象进行这种反射,您可以介绍可以将 typeTag 用于根对象,然后更深入:
def getReflectedType[T: TypeTag](val object: T)= typeTag[T]
val m = runtimeMirror(getClass.getClassLoader)
case class Aaa[T](a: T)
case class Bbb[T](l: List[T])
val a = Bbb(List.empty[Aaa[Int]])
所以你可以在这里访问该信息:
scala> getReflectedType(a).tpe
res35: reflect.runtime.universe.Type = Bbb[Aaa[Int]]
scala> getReflectedType(a).tpe.foreach(println)
Bbb[Aaa[Int]]
$line58.$read.$iw.$iw.$iw.$iw.type
$line58.$read.$iw.$iw.$iw.type
$line58.$read.$iw.$iw.type
$line58.$read.$iw.type
$line58.$read.type
$line58.type
<root>
Aaa[Int]
$line59.$read.$iw.$iw.$iw.$iw.type
$line59.$read.$iw.$iw.$iw.type
$line59.$read.$iw.$iw.type
$line59.$read.$iw.type
$line59.$read.type
$line59.type
<root>
Int
scala.type
所以您基本上可以访问该信息。
一些助手可能有用:
scala> getReflectedType(a).tpe.typeSymbol.asClass
res55: reflect.runtime.universe.ClassSymbol = class Bbb
为您提供具有 API 的 ClassSymbol(请注意,它们几乎总是将功能拆分为一些单独的 API,因此如果您看到没有任何成员的反射实体 - 尝试查找 EntityApi):
http://www.scala-lang.org/api/2.11.0-M4/index.html#scala.reflect.api.Symbols$ClassSymbolApi
scala> getReflectedType(a).tpe.declarations.toList.map(_.typeSignature)
warning: there was one deprecation warning; re-run with -deprecation for details
res67: List[reflect.runtime.universe.Type] = List(=> scala.List[T], scala.List[T], (l: scala.List[T])Bbb[T], [T](l: scala.List[T])Bbb[T], [T]=> scala.List[T] @scala.annotation.unchecked.uncheckedVariance, => java.lang.String, => scala.Int, (x$1: scala.Int)scala.Any, => Iterator[scala.Any], (x$1: scala.Any)scala.Boolean, ()scala.Int, ()java.lang.String, (x$1: scala.Any)scala.Boolean)
scala> getReflectedType(a).tpe.declarations.toList.map(x => x.name -> x.typeSignature).mkString("\n")
warning: there was one deprecation warning; re-run with -deprecation for details
res69: String =
(l,=> scala.List[T])
(l ,scala.List[T])
(<init>,(l: scala.List[T])Bbb[T])
(copy,[T](l: scala.List[T])Bbb[T])
(copy$default$1,[T]=> scala.List[T] @scala.annotation.unchecked.uncheckedVariance)
(productPrefix,=> java.lang.String)
(productArity,=> scala.Int)
(productElement,(x$1: scala.Int)scala.Any)
(productIterator,=> Iterator[scala.Any])
(canEqual,(x$1: scala.Any)scala.Boolean)
(hashCode,()scala.Int)
(toString,()java.lang.String)
(equals,(x$1: scala.Any)scala.Boolean)
为您提供成员的类型签名,我找不到方便的 apy 来将签名与 type-parameter 匹配,因此您必须手动完成(asSeenFrom 可能会有所帮助)。
2) 编译时。当您在函数中获取结构时,您可能不知道完整类型的结构。因此,您可以将WeakTypeTag 与宏一起使用。它将提供尽可能多的信息。