POJOクラスのフィールドが一致しているか否かを比較するサンプルメソッド。
- 比較元と比較先のPOJOクラスオブジェクトを引数に渡す
- publicフィールドのみが対象
- String以外だとうまくいかなかも。
- 例外処理は手抜き
private boolean compareFiledValue(Object target1, Object target2) {
Field[] fields = target1.getClass().getFields();
for (Field field : fields) {
try {
Object value1 = field.get(target1);
Object value2 = field.get(target2);
if (value1 == value2) {
continue;
}
if (value1 == null || value2 == null) {
return false;
}
if (!value1.equals(value2)) {
return false;
}
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
return false;
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
}
}
return true;
}