What is the best way to compare several javabean properties?

后端 未结 9 1824
礼貌的吻别
礼貌的吻别 2020-12-14 03:26

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 somethi

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 03:58

    While option 1 may be ugly, it will get the job done. Option 2 is even uglier, and opens your code to vulnerabilities you can't imagine. Even if you eventually rule out option 1, I pray you keep your existing code and not go for option 2.

    Having said this, you can use reflection to get a list of the field names of the class, if you don't want to pass this as a static list to the method. Assuming you want to compare all fields, you can then dynamically create the comparisons, in a loop.

    If this isn't the case, and the strings you compare are only some of the fields, you can examine the fields further and isolate only those that are of type String, and then proceed to compare.

    Hope this helps,

    Yuval =8-)

提交回复
热议问题