mercredi 5 septembre 2018

System.identityHashCode is equal on String instances

because of reasons I am trying to copy/clone instances of objects. And in the case of String i tried something like this:

I do have an object like

class Foo{
    private String test;
    //Getters && Setters are generated
}

and a copy method like:

private static Object copyMemberData(Object originalMemberData) {
    if (originalMemberData == null) {
        return null;
    }

    ...
    if (originalMemberData instanceof String) {
        return String.valueOf(originalMemberData);
    } 
    ...
}

which is used like

PropertyDescriptor propDesc = new PropertyDescriptor("test", Foo.class);
//Get Data from original object
final Object originalMemberData = propDesc.getReadMethod().invoke(originalFoo);
final Object copiedMemberData = copyMemberData(originalMemberData);

And afterwards I tried to compare the result with System.identityHashCode to ensure that I am not working on a reference.

if (System.identityHashCode(copiedMemberData) == System.identityHashCode(originalMemberData)) {
     throw new RuntimeException("Cloning is buggy!");
}

And I am suprised this actually matches and throws me an error. Maybe someone can explain me the reason for that.





Aucun commentaire:

Enregistrer un commentaire