0

I tried following code copyCustom() to copy an object and create a new object with original object content.

Once I got new object. I modified some content (String content) using get/set methods, unforturnately the contents of original object also changed.

In other words, new object referring to original object. I just need an object with deep copying without any references to original object.

    @SuppressWarnings("unchecked")
private <T> T copyCustom(T entity) throws IllegalAccessException, InstantiationException {
    Class<?> clazz = entity.getClass();
    T newEntity = (T) entity.getClass().newInstance();

    while (clazz != null) {
        copyFields(entity, newEntity, clazz);
        clazz = clazz.getSuperclass();
    }

    return newEntity;
}

private <T> T copyFields(T entity, T newEntity, Class<?> clazz) throws IllegalAccessException {
    List<Field> fields = new ArrayList<Field>();
    for (Field field : clazz.getDeclaredFields()) {
        fields.add(field);
    }
    for (Field field : fields) {

        field.setAccessible(true);
        // next we change the modifier in the Field instance to
        // not be final anymore, thus tricking reflection into
        // letting us modify the static final field
        Field modifiersField;
        try {
            modifiersField = Field.class.getDeclaredField("modifiers");
             modifiersField.setAccessible(true);
                int modifiers = modifiersField.getInt(field);
                // blank out the final bit in the modifiers int
                modifiers &= ~Modifier.FINAL;
                modifiersField.setInt(field, modifiers);
                field.set(newEntity, field.get(entity));
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    return newEntity;
}

public class Product extends ProductDataObject
{
    private static final long   serialVersionUID = -2574755579959571978L;

     private InvestmentProductKey                                   fInvestmentProductKey                   = null;
private ProductKey                                          fProductKey                             = null;
private LabelDouble                                             fTotalNetOfAssets                       = null;
private LabelString                                             fPrimaryBenchmark                       = null;
private LabelBoolean                                            fFundAgeLT3Mth                          = null;
private LabelBoolean                                            fFundAgeBTW3Mth12Mth                    = null;
private LabelBoolean                                            fFundAgeBTW12Mth36Mth                   = null;
private LabelBoolean                                            fFundAgeBTW36Mth60Mth                   = null;
private LabelBoolean                                            f
private LabelString[]                                           fGeography                              = null;
private LabelBoolean                                            fCapacityAvailableIndicator             = null;
private LabelString                                             fEquityCapitalization                   = null;
private LabelDate                                               fFiscalYearEndDate                      = null;
private LabelString                                             fFundStatus                             = null;
private LabelDate                                               fExpireDateContractExpenseLimits        = null;
private LabelDouble                                             fMaximumExpenseRatio                    = null;
private LabelString                                             fInvestments                            = null;

private YieldsAndDividends[]                                    fYieldsAndDividends                     = null;

}
Sri
  • 1,205
  • 2
  • 21
  • 52
  • Why the bold? Please format your text normally. – Boris the Spider Sep 30 '16 at 16:56
  • `field.get(entity)` returns the actual field value*, not a copy, that's probably the issue. –  Sep 30 '16 at 16:58
  • Possibles duplicate: http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java –  Sep 30 '16 at 17:00
  • @BoristheSpider took out bold text. – Sri Sep 30 '16 at 17:06
  • @RC I need to copy actual field value. But it is not. – Sri Sep 30 '16 at 17:06
  • Why can't you use a copy constructor, or (unwise) `clone()`? What is the purpose of this code? – Boris the Spider Sep 30 '16 at 17:07
  • @BoristheSpider I have an array of objects. I need to create a duplicate of same objects with some field values changed in the object. I tried to make copy of these objects and change the values of fields in copied objects. At the end array would have original objects, copied objects with some data changes. I do not think clone() will does actual copy of contents, rather referring the original object. – Sri Sep 30 '16 at 17:11
  • The comment `thus tricking reflection into letting us modify the static final field` sounds suspicious. A static field is shared between all instances of a class! Please show us the object that you want to copy too! – Thomas Kläger Sep 30 '16 at 17:11
  • @ThomasKläger original object provided.If I do not modify the "static final" field modifier, code will throw IllegalAccessException for "staic final" fields. – Sri Sep 30 '16 at 17:16
  • you must iterate each field, directly use set() if that's a primitive type else make a object copy begore setting the field. use clone() when possible. only primitive fields are copied. object are references.System.arrayCopy, but i think it copy references. – Tokazio Sep 30 '16 at 17:19

0 Answers0