0

我正在尝试检查泛型类中是否存在字段。

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
}

我该如何实现这个?

4

1 回答 1

2

2.10:

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

2.11:

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

编辑:起初没有注意到 Scala 2.10 的要求

于 2016-09-02T02:40:48.440 回答