Mikel Mikel - 1 year ago 115
Scala Question

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?

new Example(value)
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??

Answer Source


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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download