Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a flexible but <strong>slow</strong> solution based on Spring's <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-beans/3.0.3.RELEASE/org/springframework/beans/BeanUtils.java#BeanUtils.copyProperties%28java.lang.Object%2Cjava.lang.Object%2Cjava.lang.String%5B%5D%29" rel="nofollow">BeanUtils class</a></p> <pre><code>PropertyDescriptor[] descriptors = getPropertyDescriptors(YourSourceClass.class); List&lt;String&gt; ignoredProperties = new ArrayList&lt;String&gt;(); for(PropertyDescriptor pd : descriptors){ if(pd.getReadMethod().invoke(yourSourceObject) == null){ ignoredProperties.add(pg.getBaseName()); } } BeanUtils.copyProperties(yourSourceObject, yourTargetObject, ignoredProperties.toArray()); </code></pre> <p>It does away with writing an explicit null check, getter and setter for every field you may want to set.</p> <p>If you want to avoid reflection, you can shorten this construct:</p> <pre><code>if (addressDetails.getNAME3() != null) { org.setName3(addressDetails.getNAME3()); } </code></pre> <p>using a utility method like Guava's <a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Objects.html#firstNonNull" rel="nofollow"><code>Objects.firstNonNull</code></a></p> <pre><code> org.setName3(Objects.firstNonNull(addressDetails.getNAME3(), org.getName3())); </code></pre> <p>This won't help you avoid writing a line per property but it will shorten the code considerably anyway.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload