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?
getFields() returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. The method returns an array of length 0 if the class or interface has no accessible public fields, or if it represents an array class, a primitive type, or void.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
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)
You may want to take a look at this document on reflecting scala. getMethods
is a method from Java reflection. What can't you find there? From the Javadoc:
You could read more about Java reflection.
Note that not all type information will be available at runtime because of erasure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With