使用Scala反射从对象获取基元字段的类型

lmyy7pcs  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(155)

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

package myapp.model

object MyObject {
  val theInt: Option[Int]
}

在这篇文章中使用了Brian提供的ReflectionHelper。我使用getFieldType,但它返回Option[Object],而不是它本身,它是Option[Int]。该答案中的示例代码适用于Case类,例如:

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],而不是像Case类那样返回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)
  }
}
qhhrdooz

qhhrdooz1#

尝试

import scala.reflect.runtime.universe._
import scala.reflect.runtime

val runtimeMirror = runtime.currentMirror

runtimeMirror.staticClass("myapp.model.Person").typeSignature
  .member(TermName("age")).typeSignature // => Option[Int]

runtimeMirror.staticModule("myapp.model.MyObject").typeSignature
  .member(TermName("theInt")).typeSignature // => Option[Int]

相关问题