在scala反射中,如何解析具体类型的成员?
我有一个程序,在执行时可以生成一个抽象类型标签:在scala反射中,如何解析具体类型的成员?,scala,type-erasure,scala-reflect,Scala,Type Erasure,Scala Reflect,我有一个程序,在执行时可以生成一个抽象类型标签: class TypeResolving extends FunSpec { import org.apache.spark.sql.catalyst.ScalaReflection.universe._ val example = new Example it("can convert") { val t1 = implicitly[TypeTag[example.T]] println(t1) } }
class TypeResolving extends FunSpec {
import org.apache.spark.sql.catalyst.ScalaReflection.universe._
val example = new Example
it("can convert") {
val t1 = implicitly[TypeTag[example.T]]
println(t1)
}
}
object TypeResolving {
class Example {
type T = Map[String, Int]
}
val example = new Example
}
执行结果如下:
TypeTag[TypeResolving.this.example.T]
由于在本例中已定义了example.T
,因此我还希望获得实际的类型标签:
TypeTag[Map[String,Int]]
如何到达那里?试试
dealias
def dealias[T, T1](typeTag: TypeTag[T]): TypeTag[T1] = backward(typeTag.tpe.dealias)
val typeTag = implicitly[TypeTag[TypeResolving.example.T]] //TypeTag[TypeResolving.example.T]
val typeTag1 = dealias(typeTag) //TypeTag[scala.collection.immutable.Map[String,Int]]
val typeTag2 = implicitly[TypeTag[Map[String, Int]]] //TypeTag[Map[String,Int]]
val typeTag3 = dealias(typeTag2) //TypeTag[scala.collection.immutable.Map[String,Int]]
typeTag1 == typeTag3 //true
(
backward
从这里开始)尝试dealias
def dealias[T, T1](typeTag: TypeTag[T]): TypeTag[T1] = backward(typeTag.tpe.dealias)
val typeTag = implicitly[TypeTag[TypeResolving.example.T]] //TypeTag[TypeResolving.example.T]
val typeTag1 = dealias(typeTag) //TypeTag[scala.collection.immutable.Map[String,Int]]
val typeTag2 = implicitly[TypeTag[Map[String, Int]]] //TypeTag[Map[String,Int]]
val typeTag3 = dealias(typeTag2) //TypeTag[scala.collection.immutable.Map[String,Int]]
typeTag1 == typeTag3 //true
(向后
从这里开始)