mardi 5 mars 2019

Dynamically compare objects of two differents classes based solely on commons properties

I'm writing some fully dynamic methods in which I need to compare two objects of different classes.

Here is an example of the objects :

public class Object1 {

    private String lastname;
    private String firstname;
    private int age;
    private int gender;

    //All getters and setters
}

public class Object2 {

    private String lastname;
    private String address;
    private String job;

    //All getters and setters

}

As you can see here, the only common property is lastname, so I want that my comparison applies only on lastname

In addition :

  • In my real code, I use lots of different classes, I can't make them implements common interfaces, In fact, I can't modify them at all
  • I don't know which could be the commons properties, so I can't hardcode my tests
  • I'm using Java 8

So I'm looking for some class, similar to BeanUtils which has a copyProperties method for common properties, but here, instead of copying I'd like to compare.

I think this kind of utility class may exist, but I can't find one.

So if you have an idea, I'll be happy to read it :)

Thanks !

[Edit 1] More informations about why I want to do that :

I'm writing a generic system to generate endpoints for a REST Api based on JAX-RS (Jersey). I'm using interfaces with generics types like this «simple» example :

public interface sampleEndpoint<BEANPARAM,BODYREQUEST,RESPONSE>  {

    @PUT
    @Path("/{id}")
    default RESPONSE update(@Valid @BeanParam BEANPARAM bp, @Valid BODYREQUEST body) {
        //Check if id in path is the same as id in the body

        ....
    }


}

(With Jersey we can't use BeanParam to retrieve in the same Bean PathParam, QueryParam and RequestBody... here is why I need to use both, BeanParam and another bean for the body)

My use cases may be more complex, but this one is a simple illustration.





Aucun commentaire:

Enregistrer un commentaire