scala – 结构子类型反射
发布时间:2020-12-16 08:56:51 所属栏目:安全 来源:网络整理
导读:我们可以使用函数f外部的反射得到val s:String的类型吗? val f = (r: {val s: String}) = {} 解决方法 scala import scala.reflect.runtime.{universe = ru}import scala.reflect.runtime.{universe=ru}scala import scala.reflect.runtime.universe._impo
我们可以使用函数f外部的反射得到val s:String的类型吗?
val f = (r: {val s: String}) => { } 解决方法scala> import scala.reflect.runtime.{universe => ru} import scala.reflect.runtime.{universe=>ru} scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> def typeOf[T: ru.TypeTag](x: T) = ru.typeOf[T] // capture compile-time type info typeOf: [T](x: T)(implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type scala> val f = (r: {val s: String}) => {} f: AnyRef{val s: String} => Unit = <function1> scala> val tpe = typeOf(f) tpe: reflect.runtime.universe.Type = scala.AnyRef{val s: String} => Unit scala> ru.showRaw(tpe) res0: String = TypeRef(ThisType(scala),scala.Function1,List(RefinedType(List(TypeRef(ThisType(scala),newTypeName("AnyRef"),List())),Scope(newTermName("s"))),TypeRef(ThisType(scala),scala.Unit,List()))) scala> val ru.TypeRef(_,_,refinement :: _) = tpe refinement: reflect.runtime.universe.Type = scala.AnyRef{val s: String} 使用Scala反射,还可以生成结构类型的模拟,如下所示:https://gist.github.com/4008389.链接的gist使用工具箱和运行时反射执行此操作,但此方案也可以使用宏实现. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |