I want to copy a groovy object properties to another java object,and I know groovy to groovy is like this
def copyProperties(source, target) {
source.properties.each { key, value ->
if (target.hasProperty(key) && !(key in ['class', 'metaClass']))
target[key] = value
}
}
java to java I can useed apache BeanUtils, but how to copy groovy object properties to java object properties? ps: groovy object
class UserInfo {
Integer age
String userName
String password
}
java object
public class UserInfo {
private int age;
private String userName;
private String password;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
def copyProperties(source, Object target) {
source.properties.each { key, value ->
Class<? extends Object> toClass = target.getClass();
try {
BeanInfo toBean = Introspector.getBeanInfo(toClass);
PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : toPd) {
propertyDescriptor.getDisplayName();
if (key.equals(
propertyDescriptor.getDisplayName())
&& !(key in ['class', 'metaClass'])) {
if(propertyDescriptor.getWriteMethod() != null)
propertyDescriptor.getWriteMethod().invoke(target, value);
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
I got it by myself~
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.