下面的代码成功了,但是有没有更好的方法来做同样的事情?也许是特定于案例类的东西?在下面的代码中,对于我的简单案例类中的每个 String 类型的字段,代码会遍历该案例类的实例列表并找到该字段的最长字符串的长度。
case class CrmContractorRow(
id: Long,
bankCharges: String,
overTime: String,
name$id: Long,
mgmtFee: String,
contractDetails$id: Long,
email: String,
copyOfVisa: String)
object Go {
def main(args: Array[String]) {
val a = CrmContractorRow(1,"1","1",4444,"1",1,"1","1")
val b = CrmContractorRow(22,"22","22",22,"55555",22,"nine long","22")
val c = CrmContractorRow(333,"333","333",333,"333",333,"333","333")
val rows = List(a,b,c)
c.getClass.getDeclaredFields.filter(p => p.getType == classOf[String]).foreach{f =>
f.setAccessible(true)
println(f.getName + ": " + rows.map(row => f.get(row).asInstanceOf[String]).maxBy(_.length))
}
}
}
结果:
bankCharges: 3
overTime: 3
mgmtFee: 5
email: 9
copyOfVisa: 3