当尝试通过字符串名称获取对象字段时,返回值,而不是正确的scala类型。作为:

import scala.language.reflectiveCalls
import scala.language.implicitConversions

case class Intity(flag: Boolean, id: Int, name: String)
val inty =  Intity(false, 123, "blue")

implicit def reflect(r: AnyRef) = new {
  def get(n:String) = {
    val c = r.getClass.getDeclaredField(n)
    c.setAccessible(true); c}
  def getVal(n: String) = get(n).get(r)
  def getType (n:String) = get(n).getType
 }

然后当使用这个
inty.getType("flag")     // res0: Class[_] = boolean  --not Boolean
inty.getVal("id")        // res1: Object = 123    --Object not Int

任何有效的方式来实现上述实现?

最佳答案

不确定如何从一个函数返回不同的类型。
但是您可以使用scala反射api推断任何Class属性的正确类型。

import scala.reflect.runtime.{universe => ru}
implicit class ForAnyInstance[T: ru.TypeTag](i: T)(implicit c: scala.reflect.ClassTag[T]) {

    /* a mirror sets a scope of the entities on which we have reflective access */
    val mirror = ru.runtimeMirror(getClass.getClassLoader)

    /* here we get an instance mirror to reflect on an instance */
    val im = ru.runtimeMirror(i.getClass.getClassLoader)

    def fieldInfo(name: String) = {
      ru.typeOf[T].members.filter(!_.isMethod).filter(_.name.decoded.trim.equals(name)).foreach(s => {
        val fieldValue = im.reflect(i).reflectField(s.asTerm).get

        /* typeSignature contains runtime type information about a Symbol */
        s.typeSignature match {
          case x if x =:= ru.typeOf[String] => /* do something */
          case x if x =:= ru.typeOf[Int] => /* do something */
          case x if x =:= ru.typeOf[Boolean] => /* do something */
        }
      })
    }
}

然后按以下方式调用它:
case class Entity(flag: Boolean, id: Int, name: String)
val e = Entity(false, 123, "blue")
e.fieldInfo("flag")
e.fieldInfo("id")

关于scala - 如何进行反射以通过其字符串名称和原始类型获取字段值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40812987/

10-12 00:17
查看更多