【问题标题】:how to copy groovy properties to java bean properties如何将groovy属性复制到java bean属性
【发布时间】:2015-01-06 03:38:11
【问题描述】:

我想将一个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;
    }
}

【问题讨论】:

  • 您在使用copyProperties() 时遇到任何问题吗?

标签: java grails groovy


【解决方案1】:
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();
        }
    }
}

我自己弄的~

【讨论】:

  • 你还不够努力——你可以让这种方式更冗长。
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 2012-02-22
  • 2011-11-06
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2011-06-03
相关资源
最近更新 更多