0

So, suppose i have the following class:

public class Example {
   public int id,
   public String name,
   public double value,
   public int qty,

   public Example(int id, String name, double value, int qty){
      this.id = id;
      this.name = name;
      this.value = value;
      this.qty = qty;
   }
}

Then suppose i have the 2 objects:

Example example1 = new Example(1, "1", 1.0, 1);
Example example2 = new Example(2, "1", 2.0, 1);

How could i check for each field which are different from each other, without having to have a "if" statement for each field?

Edit: I need to save the history of the change in my database (like: "Value changed from 1.0 to 2.0"). That's why I need to check for the individual fields. And my class irl actually has a LOT more fields, and i'll need to do this for another classes as well. That's why I'm looking for something to do this programatically.

Soulss
  • 171
  • 1
  • 12
  • serialize to json and compare two strings – Iłya Bursov Oct 17 '22 at 14:13
  • @IłyaBursov But how would i know which fields in particular are different? I would have to compare each field of the json instead of the whole string? – Soulss Oct 17 '22 at 14:15
  • if you need to know what fields are different - you need to compare each field, there is no way around it – Iłya Bursov Oct 17 '22 at 14:16
  • 1
    and what output are you expecting? If the names and values of the fields are needed, you can use reflection - see methods of the `Class` class, like [getDeclaredFields](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/Class.html#getDeclaredFields()) – user16320675 Oct 17 '22 at 14:30
  • @user16320675 I need to save the history of the change in my database (like: "Value changed from 1.0 to 2.0"). That's why I need to check for the individual fields. And my class irl actually has a LOT more fields, and i'll need to do this for another classes as well. That's why I'm looking for something to do this programatically. – Soulss Oct 17 '22 at 14:36
  • 1
    this information is better added to the question. (my previous suggestion is still valid) – user16320675 Oct 17 '22 at 14:42
  • @user16320675 I've seen some answers about reflection. But i didn't quite understand how would I get the values (and also i'll have to mind null values like for the String in this example). – Soulss Oct 17 '22 at 14:53
  • Look at https://stackoverflow.com/questions/8001400/ – Stephen C Oct 17 '22 at 15:11
  • By the way, that kind of audit trail is often best done within the database rather than your app. – Basil Bourque Oct 17 '22 at 16:16

0 Answers0