Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best way to compare several javabean properties?
    primarykey
    data
    text
    <p>I need to compare dozens of fields in two objects (instances of the same class), and do some logging and updating in case there are differences. Meta code could look something like this:</p> <pre><code>if (a.getfield1 != b.getfield1) log(a.getfield1 is different than b.getfield1) b.field1 = a.field1 if (a.getfield2!= b.getfield2) log(a.getfield2 is different than b.getfield2) b.field2 = a.field2 ... if (a.getfieldn!= b.getfieldn) log(a.getfieldn is different than b.getfieldn) b.fieldn = a.fieldn </code></pre> <p>The code with all the comparisons is very terse, and I would like to somehow make it more compact. It would be nice if I could have a method which would take as a parameter method calls to setter and getter, and call this for all fields, but unfortunately this is not possible with java.</p> <p>I have come up with three options, each which their own drawbacks.</p> <p><b>1. Use reflection API to find out getters and setters</b><br> Ugly and could cause run time errors in case names of fields change</p> <p><b>2. Change fields to public and manipulate them directly without using getters and setters</b><br> Ugly as well and would expose implementation of the class to external world</p> <p><b>3. Have the containing class (entity) do the comparison, update changed fields and return log message</b><br> Entity should not take part in business logic</p> <p>All fields are String type, and I can modify code of the class owning the fields if required.</p> <p>EDIT: There are some fields in the class which must not be compared.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload