如何将Groovy对象的所有匹配属性分配给Java对象? [英] How to assign all matching properties from Groovy object to Java object?

查看:887
本文介绍了如何将Groovy对象的所有匹配属性分配给Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Groovy和JDBC来从表中加载一些数据。然后我想要复制属性名称匹配的属性。如何在Groovy中做到这一点?



类似这样:


sql.eachRow(select * from temp_table){

  def e = new MyJavaClass()

//将匹配字段从它复制到e

}

解决方案

除了topchef的回答,你可能会使用一些常用的地图魔法

如果您将sql限制为Java类中的属性(并假设您可以一次将整个结果保存在内存中),那么您应该可以使用 rows 方法获取 List > GroovyRowResult 对象(每行一个)。由于这个类是 Map 的一个实例,Groovy将使用它来构造你的java自动为对象

  class MyJavaClass {
字符串属性1,属性2,属性3
}

sql.rows(select property1,property2,property3 from temp_table)。each {row - >
MyJavaClass e =行
}


I want to use Groovy with JDBC to load some data from a table. I then want to copy the properties across where the property names match. How can I do this in Groovy?

Something like this:

sql.eachRow("select * from temp_table") {

        def e = new MyJavaClass()

        // copy matching fields from it to e

    }

解决方案

In addition to topchef's answer, you might be able to use some groovy map magic

If you limit your sql to the properties in your Java Class (and assuming you can hold the entire result in memory at once), then you should be able to use the rows method to get a List of GroovyRowResult objects (one per row). As this class is an instance of Map, groovy will use it to construct your java object automatically for you:

class MyJavaClass {
  String property1, property2, property3
}

sql.rows("select property1, property2, property3 from temp_table").each { row ->
   MyJavaClass e = row
}

这篇关于如何将Groovy对象的所有匹配属性分配给Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆