scala 如何在带反射的NONE上获取选项[_]的类

y1aodyip  于 2022-11-09  发布在  Scala
关注(0)|答案(2)|浏览(147)

我有这样一个设置,我想从一个XML NodeSeq填充一个对象字段。显示了我的设置的简化版本。它工作得很好,但当我把None放在testObj中时,我得到一个java.util.NoSuchElementException: None.get
我认为问题在于,当NoneNone时,我无法找到获取Option[_]的类的方法。我被困在这件事上很久了,我看不到出路。我觉得当原始值为None时,必须有一种方法来分支和填充Object字段,但如何进行呢?

import xml.NodeSeq
object test {
  case class TestObject(name: Option[String] = None, value: Option[Double] = None)
  def main(args: Array[String]): Unit = {
  val testObj = TestObject(Some("xxx"), Some(12.0))
//    val testObj = TestObject(None, Some(12.0))
    val nodeSeq = <test> <name> yyy </name> <value> 34.0 </value> </test>
    val result = getObject[TestObject](nodeSeq, Option(testObj))
    println("result = " + result) // result = Some(TestObject(Some(yyy),Some(34.0)))
  }
  def getObject[A](nodeSeq: NodeSeq, obj: Option[A]): Option[A] = {
    if ((nodeSeq.isEmpty) || (!obj.isDefined)) None else {
      for (field <- obj.get.getClass.getDeclaredFields) {
    field.setAccessible(true)
    val fieldValue = field.get(obj.get)
    if (fieldValue == null || !fieldValue.isInstanceOf[Option[_]]) None
    var newValue: Option[_] = None
    fieldValue.asInstanceOf[Option[_]].get match {    // <---- None.get is the error here
      case x: Double => newValue = Some((nodeSeq \ field.getName).text.trim.toDouble)
      case x: String => newValue = Some((nodeSeq \ field.getName).text.trim)
    }
    val decField = obj.get.getClass.getDeclaredField(field.getName)
    decField.setAccessible(true)
    decField.set(obj.get, newValue)
   }
    obj
    }
  }
}
9ceoxa92

9ceoxa921#

我忽略了这段代码中我不喜欢的其他部分,但是,您不能对None调用.get。您可以调用map,它将返回我认为您想要的结果。以下是修改后的代码:

def getObject[A](nodeSeq: NodeSeq, obj: Option[A]): Option[A] = {
    if (nodeSeq.isEmpty || obj.isEmpty) {
      None
    }
    else {
      for (field <- obj.get.getClass.getDeclaredFields) {
        field.setAccessible(true)
        val fieldValue = field.get(obj.get)
        if (fieldValue == null || !fieldValue.isInstanceOf[Option[_]]) None

        val newValue = fieldValue.asInstanceOf[Option[_]].map(a => {
          a match {
            case x: Double => Some((nodeSeq \ field.getName).text.trim.toDouble)
            case x: String => Some((nodeSeq \ field.getName).text.trim)
          }
        })

        val decField = obj.get.getClass.getDeclaredField(field.getName)
        decField.setAccessible(true)
        decField.set(obj.get, newValue)
      }
      obj
    }
  }

在实践中,我通常避免对选项调用.get,因为它经常导致错误。

更新:

这个版本的功能更强大一些,但它仍然会更改您发送的obj:

def getObject[A](nodeSeq: NodeSeq, obj: Option[A]): Option[A] = {
    obj.map(o => {
      for {
        field <- o.getClass.getDeclaredFields
        _ = field.setAccessible(true)
        fieldValue <- Option(field.get(o))
      } yield {
        val newValue = fieldValue match {
          case Some(a) => {
            a match {
              case x: Double => Some((nodeSeq \ field.getName).text.trim.toDouble)
              case x: String => Some((nodeSeq \ field.getName).text.trim)
            }
          }
          case _ => None
        }
        val decField = o.getClass.getDeclaredField(field.getName)
        decField.setAccessible(true)
        decField.set(o, newValue)
      }
      o
    })
  }
xoshrz7s

xoshrz7s2#

实际上,这可能更接近您想要的结果:请检查字段的类型。

import xml.NodeSeq
object test {
  case class TestObject(name: Option[String] = None, value: Option[Double] = None)
  def main(args: Array[String]): Unit = {
  val testObj = TestObject(Some("xxx"), Some(12.0))
//    val testObj = TestObject(None, Some(12.0))
    val nodeSeq = <test> <name> yyy </name> <value> 34.0 </value> </test>
    val result = getObject[TestObject](nodeSeq, Option(testObj))
    println("result = " + result) // result = Some(TestObject(Some(yyy),Some(34.0)))
  }
  def getObject[A](nodeSeq: NodeSeq, obj: Option[A]): Option[A] = {
    if ((nodeSeq.isEmpty) || (!obj.isDefined)) None else {
      for (field <- obj.get.getClass.getDeclaredFields) {
    field.setAccessible(true)
    val newValue = field.getGenericType match {
      case t: ParametrizedType if (t.getActualType == classOf[Option[_]]) => 
        val paramType = t.getActualTypeArguments()(0)
        if (paramType == classOf[java.lang.Double]) // since Double can't be a generic type parameter on JVM
          // from your original code, but it probably needs to be modified
          // to handle cases where field isn't in nodeSeq or not a number
          Some((nodeSeq \ field.getName).text.trim.toDouble) 
        else if (paramType == classOf[String])
          Some((nodeSeq \ field.getName).text.trim)
        else None
      case _ => None
    }
    if (newValue.isDefined)
      field.set(obj.get, newValue)
   }
    obj
    }
  }
}

创建新对象的版本(可能需要根据您的要求进行修改):

def getObject[A](nodeSeq: NodeSeq, objClass: Class[A]): Option[A] = {
    if (nodeSeq.isEmpty) None else {
      try {
        val fieldValues = objClass.getDeclaredFields.flatMap { field =>
          field.setAccessible(true)
          field.getGenericType match {
            case t: ParametrizedType if (t.getActualType == classOf[Option[_]]) => 
              val paramType = t.getActualTypeArguments()(0)
              if (paramType == classOf[java.lang.Double])
                Some(Some((nodeSeq \ field.getName).text.trim.toDouble))
              else if (paramType == classOf[String])
                Some(Some((nodeSeq \ field.getName).text.trim))
              else None
            case _ => None
          }
        }
        // assumes only one constructor, otherwise get the desired one
        val ctor = objClass.getConstructors()(0)
        Some(ctor.newInstance(fieldValues))
      } catch {
        case _ => None
      }
    }
  }

相关问题