有没有办法在Scala中以通用类型调用成员

时间:2019-04-30 03:25:58

标签: scala reflection generic-programming

我正在尝试从通用类型调用成员,这是运行函数的原始方式

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)

然后在流程函数中,如何为成员分配值

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

已解决

Convert Any Class to HashMap

2 个答案:

答案 0 :(得分:1)

查看您的代码,似乎您不想“调用泛型类型的成员”,似乎希望将案例类转换为HashMap

Case class to map in Scala

答案 1 :(得分:0)

这里是小片段

-- insert test
INSERT TestTableLog(ID,Title,OperType)
EXEC InsTestTable 1,'A'

INSERT TestTableLog(ID,Title,OperType)
EXEC InsTestTable 2,'B'

INSERT TestTableLog(ID,Title,OperType)
EXEC InsTestTable 3,'C'

-- update test
INSERT TestTableLog(ID,Title,OperType)
EXEC UpdTestTable 2,'BBB'

-- delete test
INSERT TestTableLog(ID,Title,OperType)
EXEC DelTestTable 3
GO

-- show resutls
SELECT *
FROM TestTableLog

使用赋值

  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)