繁体   English   中英

如何将Groovy属性复制到Java bean属性

[英]how to copy groovy properties to java bean properties

我想将一个groovy对象的属性复制到另一个java对象,并且我知道groovy到groovy就像这样

def copyProperties(source, target) {
    source.properties.each { key, value ->
        if (target.hasProperty(key) && !(key in ['class', 'metaClass']))
            target[key] = value
    }
}

从Java到Java我可以使用apache BeanUtils,但是如何将Groovy对象属性复制到Java对象属性? ps:常规对象

class UserInfo {
    Integer age
    String userName
    String password
}

Java对象

 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();
        }
    }
}

我一个人知道的〜

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM