我使用了一种时髦的方式来做到这一点: https://stackoverflow.com/a/9072974/4470135 所以我的代码是:
def copyProperties(source, target) {
def (sProps, tProps) = [source, target]*.properties*.keySet()
def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
commonProps.each { target[it] = source[it] }
}
当我尝试调用将实体转换为 Dto 的方法时,我得到的是:
No signature of method: java.util.ArrayList.keySet() is applicable for argument types: () values: []\nPossible solutions: toSet(), toSet(), set(int, java.lang.Object), set(int, java.lang.Object), get(int), get(int)
更新:
我的源是一个带有字段的可序列化 bean:
private String passengerName;
@NotNull
@Size(min = 5, max = 40)
private String destination;
@NotNull
private String departureDate;
我的目标是具有相同字段的 JPA 实体,但具有附加的 @Id 字段和略有不同的日期表示形式:
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
ZonedDateTime departureDate
最佳答案
User user = User.findById('1')
User copyUser = new User()
InvokerHelper.setProperties(copyUser, user.properties)
关于java - 将对象属性复制到 Groovy 中的另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46952475/