scala case class和普通class 动态参数赋值

普通class赋值,将A类的属性赋值给B类

//动态赋值测试
object DynamicAssignmentTest {

  def main(args: Array[String]): Unit = {
    var aList = List(
      new A1("A1", 12),
      new A1("A2", 13),
    )

    val b1List = scala.collection.mutable.ListBuffer[B1]()
    aList.foreach(
      a => {
        val b = new B1()
        classOf[A1].getDeclaredFields.foreach(f => {
          f.setAccessible(true)
          val bField = b.getClass.getDeclaredField(f.getName)
          bField.setAccessible(true)
          bField.set(b, f.get(a).toString)
        })
        b1List.append(b)
      }
    )

    b1List.toList.foreach(println)
  }

}

class A1 {
  var name: String = _
  var age: Int = _

  def this(name: String, age: Int) {
    this()
    this.name = name
    this.age = age
  }
}

class B1 {
  var name: String = _
  var age: String = _
  var sex: String = _
  var birthday: String = _
  var phone: String = _
}

case Class赋值,需要先利用构造函数 创建出一个对象需要传递参数

object CaseClassTest {
  def main(args: Array[String]): Unit = {

    val a = F(null, null)
    classOf[F].getDeclaredFields.foreach(f => {
      f.setAccessible(true)
      //注意:value的类型得时string,如果是Int 或者别的类型需要.tostring ,否则会类型转换错误
      f.set(a, "123")
    })

    println(a)
  }
}

case class F(var name: String, var age: String)

posted @ 2023-07-06 09:32  iullor  阅读(143)  评论(0编辑  收藏  举报