Scala 类.getFields [英] Scala Class.getFields

查看:46
本文介绍了Scala 类.getFields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了我的应用程序的目的,我需要能够在运行时找出类型(不是实例)的字段列表和这些字段的类型.到目前为止,我只能通过 classOf[MyCaseClass].getMethods 获取包含 getter 的案例类的方法列表,而从简单的类中没有任何用处.我错过了什么吗?是否有用于这种目的的反射库?这是如何正确完成的?

For purposes of my app I need to be able to find out a list of fields of a type (not an instance) and types of those fields in runtime. So far I was only able to get a list of methods of a case class containing getters with classOf[MyCaseClass].getMethods and nothing useful from a simple class. Am I missing something? Are there any reflection libraries for that kinda purposes? How's that done correctly?

推荐答案

使用 Scala 2.10 反射:

Using Scala 2.10 reflection:

scala> import reflect.runtime.{universe => ru}
import reflect.runtime.{universe=>ru}
scala> trait A { val field1: Int; val field2: Char; def meth1: Int }
defined trait A
scala> val fieldSymbols = ru.typeOf[A].members.collect{ case m: ru.MethodSymbol if m.isGetter => m }
fieldSymbols: Iterable[reflect.runtime.universe.MethodSymbol] = List(value field2, value field1)

返回的符号包含所有类型信息,例如:

The returned symbols contain all the type information, e.g.:

scala> fieldSymbols.map(_.typeSignature)
res16: Iterable[reflect.runtime.universe.Type] = List(=> scala.Char, => scala.Int)

这篇关于Scala 类.getFields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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