有没有办法在 Scala 中调用泛型类型的成员

Is there a way to call a member in a generic type in Scala

我正在尝试从泛型类型调用成员,这是 运行 函数

的原始方法

SourceStruct 是我想用 T.

之类的东西替换的对象
override def process(t: SourceStruct, runtimeContext: RuntimeContext, requestIndexer: RequestIndexer): Unit = {
        val json = new util.HashMap[String, String]()
        json.put("time", t.rating.toString)
        json.put("userId", t.userId.id.toString)
        json.put("itemId", t.itemId.id)

        requestIndexer.add(request)
      }

当我将 SourceStruct 替换为 T 时,如何调用 t.userId

override def process(t: T, runtimeContext: RuntimeContext, requestIndexer: RequestIndexer): Unit = {
      val json = new util.HashMap[String, String]()
//      json.put("userId", t.userId.id)
//      json.put("itemId", t.itemId.id)
//      json.put("rating", t.rating.toString)

      val request = Requests
        .indexRequest()
        .index(index)
        .`type`(indexType)
        .source(json)
      requestIndexer.add(request)
    }

提前致谢

我可以使用

获取成员
typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList

但对上面的问题还是一头雾水


编辑:

例如:

case class ExampleClass(x: Int, y: Int)
case class ExampleClass2(xx: Int, yy: Int)

那么在process函数中,如何给member赋值

override def process(t: T, ...) = {
    //t.x = 10 or t.xx = 10 ???
}

已解决

Convert Any Class to HashMap

这是小片段

  case class Foo(bar: String)

  val f: Object = Foo("a")

  val barField = f.getClass.getDeclaredField("bar")

  barField.setAccessible(true)
  val value = barField.get(f).asInstanceOf[String]

  print(value)

赋值使用

 barField.set(f, "new value")

看你的代码,你似乎不想 "to call a member in a generic type",你似乎想将案例 class 转换为 HashMap

Case class to map in Scala