加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何将groovy属性复制到java bean属性

发布时间:2020-12-14 16:21:40 所属栏目:大数据 来源:网络整理
导读:我想将一个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 to
我想将一个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 to 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();
        }
    }
}

我自己得到了?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读