使用Scala反射从对象获取原始字段的类型

时间:2019-02-27 20:54:47

标签: scala reflection scala-reflect

因此,我尝试获取Scala对象类中每个字段的类型:

package myapp.model

object MyObject {
  val theInt: Option[Int]
}

使用Brian在this post中提供的ReflectionHelper。我使用getFieldType,但是它返回的是Option[Object],而不是Option[Int]。该答案中的示例代码适用于案例类,例如:

package myapp.model

case class Person(
 name: String,
 age: Option[Int]
)

scala> ReflectionHelper.getFieldType("myapp.model.Person", "age")  // int
res12: Option[reflect.runtime.universe.Type] = Some(Option[Int])

但是,如果我在Scala对象字段上运行getFieldType,我们会得到:

scala> ReflectionHelper.getFieldType("myapp.model.MyObject$", "theInt")
res10: Option[reflect.runtime.universe.Type] = Some(Option[Object])

导致这种行为的Scala对象有什么不同?如何使getFieldType返回Option[Int]而不是返回Option[Object],就像案例类一样?

为方便起见,这里是另一个问题的ReflectionHelper:

import scala.reflect.runtime.{ universe => u }
import scala.reflect.runtime.universe._

object ReflectionHelper {

  val classLoader = Thread.currentThread().getContextClassLoader

  val mirror = u.runtimeMirror(classLoader)

  def getFieldType(className: String, fieldName: String): Option[Type] = {

    val classSymbol = mirror.staticClass(className)

    for {
      fieldSymbol <- classSymbol.selfType.members.collectFirst({
        case s: Symbol if s.isPublic && s.name.decodedName.toString() == fieldName => s
      })
    } yield {

      fieldSymbol.info.resultType
    }
  }

  def maybeUnwrapFieldType[A](fieldType: Type)(implicit tag: TypeTag[A]): Option[Type] = {
    if (fieldType.typeConstructor == tag.tpe.typeConstructor) {
      fieldType.typeArgs.headOption
    } else {
      Option(fieldType)
    }
  }

  def getFieldClass(className: String, fieldName: String): java.lang.Class[_] = {

    // case normal field return its class
    // case Option field return generic type of Option

    val result = for {
      fieldType <- getFieldType(className, fieldName)
      unwrappedFieldType <- maybeUnwrapFieldType[Option[_]](fieldType)
    } yield {
      mirror.runtimeClass(unwrappedFieldType)
    }

    // Consider changing return type to: Option[Class[_]]
    result.getOrElse(null)
  }
}

1 个答案:

答案 0 :(得分:2)

尝试

// import scala.reflect.runtime.universe._  
mirror.staticClass("myapp.model.Person").typeSignature.member(TermName("age")).typeSignature // => Option[Int]    
mirror.staticModule("myapp.model.MyObject").typeSignature.member(TermName("theInt")).typeSignature // => Option[Int]