mardi 2 juin 2015

Is there any way to compare only some attributes of two objects in java

In java is there any way to compare only some attributes of two objects and show the differance between these fields, i cant override the equals method.( i need to configure list of some attributes of the object not all attributes of object)

I can use reflation. eg :

class Motorcycle
{
    int year;
    String make;
    String model; 
    float purchasePrice;
    float resalePrice;
}

class CompareResult 
{
    String screenDisplayName;
    String valueInObject1;
    String valueInObject2;
    boolean isMatching;
}

I can configure the fields in some xml or some custom list with attributes like

<screendisplayname="Make" attribute ="motorcycle.make">
<screendisplayname="Year" attribute ="motorcycle.year">

so if our xml is having only 2 attributes then it should compare only these 2 attributes,(out utility will pick data from the xml and comapre only given attributes dynamically)

Class ComapreObjectTest {

    psvm () {
        Motorcycle m1 = new motorcycle();
        m1.year = 2011;
        m1.make = "Honda";
        m1.model="CBR";

        Motorcycle m2 = new motorcycle();
        m2.year = 2015;
        m2.make = "Suzuki";
        m2.model="Hayabusa";

        List<CompareResult> compareResultList = comapreObjects(m1,m2);
        /*  so our list will be having following data   

            compareResultList[0].screenDisplayName -> Make
            compareResultList[0].valueInObject1 -> Honda
            compareResultList[0].valueInObject2 -> Suzuki
            compareResultList[0].isMatching -> false

            compareResultList[1].screenDisplayName -> Year
            compareResultList[1].valueInObject1 -> 2011
            compareResultList[1].valueInObject2 -> 2015
            compareResultList[1].isMatching -> false

        */
    }
}





Aucun commentaire:

Enregistrer un commentaire