Scala Class.getFields

前端 未结 2 1417
北恋
北恋 2020-12-17 23:07

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 ab

相关标签:
2条回答
  • 2020-12-17 23:55

    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)
    
    0 讨论(0)
  • 2020-12-18 00:08

    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.

    0 讨论(0)
提交回复
热议问题