Create a child class object based on a parent one

Weijun Wang at
Fri Aug 8 00:10:22 UTC 2014

I have a class A and a sub class B. B contains no extra fields than A.

Now there is an object of A and I want to create a B which is 
"identical" to it. What I am doing is

         public B(A old) {
             for (Field f: A.class.getDeclaredFields()) {
                 if (!Modifier.isStatic(f.getModifiers())) {
                     try {
                         f.set(this, f.get(old));
                     } catch (Exception e) {
                         throw new RuntimeException(e);

Is there a better way to do this? I can think of Unsafe.

Please note I cannot put an A inside B because there are instanceof 
calls that B must isa A. Also, the A object will be discarded so there 
is no need to clone the fields.


More information about the core-libs-dev mailing list