如何通过 scala-reflect 和 TypeTag (Scala 2.10) 访问通用 class 字段
How to access to generic class field via scala-reflect and TypeTag (Scala 2.10)
我正在尝试检查泛型 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
}
我该如何实现这个?
我正在尝试检查泛型 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
}
我该如何实现这个?