title: Compare fields with same name of objects of different classes in Java
body: <p>I have two objects, each of which have tens of fields:</p>
  
  <pre><code>Class1 {
      int firstProperty;
      String secondProperty;
      String anotherProperty1;
      ...
  }
  
  Class2 {
      int firstProperty;
      String secondProperty;
      String anotherProperty2;
      ...
  }
  </code></pre>
  
  <p>some of the method names are exactly same, others are not, for example here, they all have <code>firstProperty</code> and <code>secondProperty</code> and they are same in name. but other fields are not same. What is an elegant way to know if the values of every same field of two objects of the two class is actually same?</p>
  
  <p>_________________________________UPDATE_____________________________________</p>
  
  <p>I'm still not sure why some people still think it is exactly the duplicate question. Since the question is closed, I have to paste my solution here.</p>
  
  <pre><code>private boolean hasChanged(Object o1, Object o2){
  
      if (o1 == null || o2 == null) {
          return true;
      }
  
      Class clazz1 = o1.getClass();
      Class clazz2 = o2.getClass();
      for (Method method1 : clazz1.getDeclaredMethods()) {
          for (Method method2 : clazz2.getDeclaredMethods()) {
              try {
                  if (method1.getName().startsWith("get") &amp;&amp; method1.getName().equals(method2.getName())) {
                      if (method1.invoke(o1, null) == null &amp;&amp; method2.invoke(o2, null) == null) {
                          continue;
                      } else if (method1.invoke(o1, null) == null || method2.invoke(o2, null) == null) {
                          continue;
                      } else if (!method1.invoke(o1, null).equals(method2.invoke(o2, null))) {
                          return true;
                      }
                  }
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              } catch (InvocationTargetException e) {
                  e.printStackTrace();
              }
          }
      }
      return false;
  }
  </code></pre>