2015-01-06 1 views
4
나는 다른 자바 객체에 끝내 개체 속성을 복사 할

에 끝내 속성을 복사하기 위해, 나는 당연 할 그루비 알고 내가 아파치 BeanUtils를 useed 수 있습니다 자바이어떻게 자바 빈 속성

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

자바처럼, 그루비 개체 속성을 Java 개체 속성에 복사하는 방법은 무엇입니까? PS : 그루비 객체

class UserInfo { 
    Integer age 
    String userName 
    String password 
} 

자바 객체

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; 
    } 
} 
+0

당신이'copyProperties를 사용하는 문제를 (에 직면 마 ~ 나 자신에 의해 그것을 가지고)'같은 하시나요? – dmahapatro

답변

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

내가

+2

당신은 충분히 열심히 노력하고 있지 않습니다 - 당신은 그렇게 길게 만들 수 있습니다. –