简体   繁体   中英

Get two different class instances and compare them (Java)

I am receiving input from my Ext JS application on the front end and I want to compare two records on the java side, the record prior to a form update on the UI side and the record after setting all the new values. I have made two references to the same type of object, one before setting new values ( oldRecord ) and one after ( newRecord ) and compare these but when I try to use oldRecord.getClass() on the old record it will show the new field values. Is there any way to have access to the old values? I also tried making two field arrays and passing those into my method.

private static Map<String, List<String>> changes;

public static <T> Map<String, List<String>> getChanges (T oldRecord, T newRecord) {

    changes = new HashMap<String, List<String>>();

    try {
        if(oldRecord instanceof UserInfo && oldRecord.getClass().equals(newRecord.getClass())) {
            Field field = oldRecord.getClass().getDeclaredField("name");
            field.setAccessible(true);
            System.out.println(field.get(oldRecord));
            field = newRecord.getClass().getDeclaredField("name");
            field.setAccessible(true);
            System.out.println(field.get(newRecord));

            // will loop through all fields in both records and compare

        }
    } catch (Exception e) {
        System.err.println("Exception");
    }

    return changes;
}

I think you are using the same object. This is the case if you have done something like this:

Object oldRecord = new Object();
Object newRecord = oldRecord;
newRecord.doSomethingThatModifyIt();
getChanges(oldRecord, newRecord);

If you have done something like this, then keep in mind that Object newRecord = oldRecord; does not create any new object, but just sets the 2 variables to point to the same object.

You should instead create a new object based on the old one, with some method like clone() that you would have to implement. Or just by manually setting the fields of the newly created object.

Note: I have used Object but it could be any type of course.

If oldRecord and newRecord reference the same object like

T oldRecord = new T();
T newRecord = oldRecord;

they will "hold" the same instance variable values as well.

To save in oldRecord the old values you must do a deep copy of the object, that means create a new object and copy the instance variable values.

SEarch for deep copy or cloning, maybe start here: How do you make a deep copy of an object in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM