LoginSignup
4
5

More than 5 years have passed since last update.

POJOのフィールドの値が同一か比較する

Last updated at Posted at 2014-01-04

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;
    }
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5