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())) {
                    f.setAccessible(true);
                    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.

Thanks
Max

Reply via email to