Note that there are some explanatory texts on larger screens.

plurals
  1. POCopy all values from fields in one class to another through reflection
    primarykey
    data
    text
    <p>I have a class which is basically a copy of another class.</p> <pre><code>public class A { int a; String b; } public class CopyA { int a; String b; } </code></pre> <p>What I am doing is putting values from class <code>A</code> into <code>CopyA</code> before sending <code>CopyA</code> through a webservice call. Now I would like to create a reflection-method that basically copies all fields that are identical (by name and type) from class <code>A</code> to class <code>CopyA</code>.</p> <p>How can I do this?</p> <p>This is what I have so far, but it doesn't quite work. I think the problem here is that I am trying to set a field on the field I am looping through.</p> <pre><code>private &lt;T extends Object, Y extends Object&gt; void copyFields(T from, Y too) { Class&lt;? extends Object&gt; fromClass = from.getClass(); Field[] fromFields = fromClass.getDeclaredFields(); Class&lt;? extends Object&gt; tooClass = too.getClass(); Field[] tooFields = tooClass.getDeclaredFields(); if (fromFields != null &amp;&amp; tooFields != null) { for (Field tooF : tooFields) { logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString()); try { // Check if that fields exists in the other method Field fromF = fromClass.getDeclaredField(tooF.getName()); if (fromF.getType().equals(tooF.getType())) { tooF.set(tooF, fromF); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>I am sure there must be someone that has already done this somehow</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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