Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Class.getFields

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?

like image 452
Nikita Volkov Avatar asked Oct 10 '11 04:10

Nikita Volkov


People also ask

What is getFields?

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.

How to get fields of object in Java?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


2 Answers

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)
like image 158
Nikita Volkov Avatar answered Sep 22 '22 06:09

Nikita Volkov


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:

  • String getName(): Returns the name of the method represented by this Method object, as a String.
  • Class[] getParameterTypes(): Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object.
  • Class getReturnType(): Returns a Class object that represents the formal return type of the method represented by this Method object.

You could read more about Java reflection.

Note that not all type information will be available at runtime because of erasure.

like image 41
schmmd Avatar answered Sep 18 '22 06:09

schmmd