scalascala-reflectscala-generics

How to access to generic class field via scala-reflect and TypeTag (Scala 2.10)


I am trying to check if a field exists in a generic class.

import scala.reflect.runtime.{universe => ru}    
class Example[T:ru.TypeTag](val value:T)

object Example {
  def apply[T:ru.TypeTag](value:T, fieldName: String) : Example[T] = {
    val t = ru.typeOf[T]
    val hasField: Boolean = ??? // HOW CAN I CHECK THAT class T has the field with name fieldName?

    if(hasField)
      new Example(value)
    else
      throw new RuntimeException()
  }
}

case class Foo(field:String)
object Test{
  Example(Foo("hola"), "field") // WILL WORK
  Example(Foo("hola"), "other") // THROWS EXCEPTION
}

How can I implement this??


Solution

  • 2.10:

    val hasField = t.declarations.exists { _.name.decodedName.toString == fieldName }
    

    2.11:

    val hasField = t.decls.exists { _.name.decodedName.toString == fieldName }
    

    edit: didn't notice the Scala 2.10 requirement at first