title: Is there a way to instantiate a child class with parent object in java?
body: <p>I have a base class say </p>
  
  <pre><code>class A {
     private String name;
     private String age;
  
     //setters and getters for same
  }
  </code></pre>
  
  <p>and a child class say</p>
  
  <pre><code>class B extends A {
   private String phone;
   private String address;
  
    //setters and getters for same
  }
  </code></pre>
  
  <p>now I've an instance of A and besides this I have to set the fields in B as well, so code would be like,</p>
  
  <pre><code>A instanceOfA = gotAFromSomewhere();
  B instanceOfB = constructBFrom(instanceOfA);
  instanceOfB.setPhone(getPhoneFromSomewhere());
  instanceOfB.setAddress(getAddressFromSomewhere());
  </code></pre>
  
  <p>can I instantiate B with given A, but <strong>I don't want to do this way</strong>,</p>
  
  <pre><code>B constructBFrom(A instanceOfA) {
    final B instanceOfB = new B();
    instanceOfB.setName(instanceOfA.getName());
    instanceOfB.setPhone(instanceOfA.getAge());
  
    return B;
  }
  </code></pre>
  
  <p>rather what I'd love to have some utility with function which is generic enough to construct object as in,</p>
  
  <pre><code>public class SomeUtility {
  
     public static &lt;T1, T2&gt; T2 constructFrom(T1 instanceOfT1, Class&lt;T2&gt; className) {
  
        T2 instatnceOfT2 = null;
  
        try {
           instatnceOfT2 = className.newInstance();
           /*
           * Identifies the fields in instanceOfT1 which has same name in T2
           * and sets only these fields and leaves the other fields as it is.
           */
        } catch (InstantiationException | IllegalAccessException e) {
           // handle exception
        }          
  
        return instatnceOfT2;
     }
  }
  </code></pre>
  
  <p>so that I can use it as,</p>
  
  <pre><code>B constructBFrom(A instanceOfA) {
     return SomeUtility.constructFrom(instanceOfA, B.class);
  }
  </code></pre>
  
  <p>Moreover, use case will not be only limited to parent-child classes, rather this utility function can be used for adapter use cases.</p>
  
  <p><strong>PS- A and B are third party classes I've to use these classes only so I can't do any modifications
  in A and B.</strong></p>