我需要比较两个对象(同一个类的实例)中的数十个字段,并在有差异时进行一些记录和更新。元代码可能看起来像这样:
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
代码中的所有比较都非常简洁,我希望能够更加紧凑一些。如果我能够有一个方法来接受setter和getter的方法调用作为参数,并对所有字段调用它,那就太好了。但很遗憾,这在Java中是不可能的。我想到了三种选择,每种选择都有自己的缺点。
1. 使用反射API查找getter和setter
丑陋,如果字段名称更改,可能会导致运行时错误。
2. 将字段更改为public并直接操作它们,而不使用getter和setter
同样丑陋,并将类的实现暴露给外部世界。
3. 让包含类(实体)进行比较,更新已更改的字段并返回日志消息
实体不应参与业务逻辑。
所有字段都是字符串类型,如果需要,我可以修改拥有字段的类的代码。
编辑:该类中有一些字段不得进行比较。