簡體   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