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

标签 java grails groovy

我想将一个 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 对象属性? 附言: 常规对象

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

我自己搞定的~

关于java - 如何将 groovy 属性复制到 java bean 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791718/

相关文章:

json - 有没有办法向 Grails JSON 响应添加额外的字段?

grails - 如何检查 groovy 脚本是否存在编译错误

hibernate - Grails Map <String,Object>导致异常Integer无法转换为String

gradle - 如何在build.gradle中定义和调用自定义方法?

java - 编译组、名称等是什么?

java - 当鼠标在 MATLAB 中传递静态文本时更改鼠标光标

java - java中这个有效的泛型方法如何?

Java - 从接受泛型的类继承?

java - 为什么调用另一个抛出 RuntimeException 的方法需要 return 语句?

web-services - Grails:不同格式的RESTful Web服务数据处理