Compare objects of different classes using reflection

java compare two objects and get differences
java compare two objects field by field
compare 2 objects
how to compare two objects in java
java compare two objects attributes
how to compare two pojo objects in java
compare two custom objects in java
java check if two objects are the same instance

I've got two objects with exactly the same attributes. Don't ask me why, this is generated code and I have to deal with this.

class Bean1 {
   int id;
}

class Bean2 {
   int id;
}

I want to compare objects of each class without writing the compare code for each attribute. This thread explains how to compare two objects but in my case this fails because they are not of instances of the same class.

This code returns false:

EqualsBuilder.reflectionEquals(new Bean1(1), new Bean2(1));

Is there another way to comapre objects and ignore object classes?

How to compare objects using Reflection in C#Everything Technical, How to compare objects using Reflection in C# Finally, if the value is another class object , we have to employ the whole logic again for those  As part of the refactoring I was doing to the load code for crawler projects I needed a way of verifying that new code was loading data correctly. As it would be extremely time consuming to manually compare the objects, I used Reflection to compare the different objects and their properties. This article briefly describes the process and provides a complete helper function you can use in your

I was finally able to do this with Apache Common Lang's ReflectionToStringBuilder, because it provides a ToStringStyle.NO_CLASS_NAME_STYLE option.

Furthermore, as I'm using it with JUnit test, it's useful because if the objects are differents, I will be able to see which field is different.

Assert.assertEquals(
   new ReflectionToStringBuilder(bean1, ToStringStyle.NO_CLASS_NAME_STYLE).toString(),
   new ReflectionToStringBuilder(bean2, ToStringStyle.NO_CLASS_NAME_STYLE).toString());

Use reflection to compare getters on two objects · GitHub, ArrayList;. import java.util.List;. import org.apache.commons.lang.builder.​EqualsBuilder;. /**. * Class that utilizes reflection to help in testing. You don't necessarily need reflection to perform the comparison. You can write a comparer class that takes two instances of Employee or Address, and compares each field that should match. For any that don't match, you can add a string (or PropertyInfo ) element to some list to return to the caller.

If your entities have common attributes use an abstract class and override equals method

abstract class Bean {
   private int id;


   public int getId(){
      return id;
   }    

   @Override
   boolean equals(Object obj){
      if(obj is null){
        return false; 
      } else if (obj instanceof Bean) {
          return ((Integer)this.getId()).equals((Bean)obj).getId());
      } else {
         return false;
      }
   }
}

class Bean1 extends Bean {
   //int id;
}

class Bean2 extends Bean  {
   //int id;
}

Comparing field values using reflection, I am trying to compare the field values of two different objects in a generic way. I was googling and I saw that C# had like a PropertyInfo Class - does Java have Use reflection to compare the properties of two objects, 5) I am not sure why  As it would be extremely time consuming to manually compare the objects, I used Reflection to compare the different objects and their properties. This article briefly describes the process and provides a complete helper function you can use in your own projects.

You can use reflection as workaround for your problem, but the best way to do it will be as @imperezivan said, using a common ancestor to have the attributes in the same place.

A reflection implementation will be as easy as getting all the fields of each object, and compare its values. Here you have an example:

public static boolean compareObjects(Object o1, Object o2) {        
        try {
            List<Field> fields1 = getFields(o1);
            List<Field> fields2 = getFields(o2);
            boolean found;
            Field field2Temp = null;
            for (Field field1 : fields1) {
                found = false;
                for (Field field2 : fields2) {
                    if (field1.getName().equals(field2.getName())) {
                        if (!field1.get(o1).equals(field2.get(o2))) {
                            System.out.println("Value " + field1.get(o1) + " for field " + field1 + " does not match the value " + field2.get(o2) + " for field " + field2);
                            return false;
                        }
                        field2Temp = field2;
                        found = true;
                    }
                }
                if (!found) {
                    System.out.println("Field " + field1 + " has not been found in the object " + o2.getClass());
                    return false;
                } else {
                    fields2.remove(field2Temp);
                }
            }
            if (fields2.size() > 0) {
                for (Field field : fields2) {
                    System.out.println("Field " + field + " has not been found in the object " + o1.getClass());
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static List<Field> getFields(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
        }
        return new ArrayList<>(Arrays.asList(fields));
    }

As you can see I'm forcing the fields to match, so if one field is not found in the other object, the method will return false, but you can easily change it depending on your needs.

This code gives some details about where the problem is if two objects are different.

With this execution:

public static void main(String args[]){
        Bean1 bean1 = new Bean1(1);
        Bean2 bean2 = new Bean2(1);
        System.out.println("Equals? " + bean1.equals(bean2));
        System.out.println("Reflection equals? " + compareObjects(bean1, bean2));
        bean2 = new Bean2(2);
        System.out.println("Equals? " + bean1.equals(bean2));
        System.out.println("Reflection equals? " + compareObjects(bean1, bean2));
    }

The results you get are:

Equals? false
Reflection equals? true
Equals? false
Value 1 for field private int com.test.so.Bean1.id does not match the value 2 for field private int com.test.so.Bean2.id
Reflection equals? false

If you plan to use this code, please test the edge cases as I haven't done it

Use reflection to compare the properties of two objects, Any value other than zero would indicate that at least one property on the objects are not equal. This method may have interest to people who  Since the O/R mapper and FileHelpers used the same class, using this comparison method to determine if the objects were “equal” let me determine whether or not the data loaded from the database was different from the data in the text file. Even though it used reflection, there wasn’t a huge performance hit, either.

Guide to Java Reflection, We then use reflection to retrieve the object name and field names. Then the other two methods return the fully qualified class name including of a class but for now, it suffices to just get their names and compare them with  What you have been waiting for. Perform a deep compare of any two .NET objects using reflection. Shows the differences between the two objects. Compatibility. Compatible with .NET Framework 4.0 and higher.

Comparing the properties of two objects via Reflection and C# , Some properties are simple types, such as an int or a string and are very easy to compare. What happens if a property returns some other object  In this guide I explained two ways to copy properties from one object to another. If you face a similar situation in your projects, instead of writing multiple lines of code, you can just use these classes or extension methods to copy the needed properties from one object to the other object.

Reflection, On the Java platform, the runtime component required for using the reflection features You can get the reference to a class of a specific object with the same ::class Compare the types of bound and the corresponding unbound references. The following example uses Equals to compare two types. using System; using System.Reflection; class Example { public static void Main() { Type a = typeof(System.String); Type b = typeof(System.Int32); Console.WriteLine (" {0} == {1}: {2}", a, b, a.Equals (b)); // The Type objects in a and b are not equal, // because they represent different types. a = typeof(Example); b = new Example ().GetType (); Console.WriteLine (" {0} is equal to {1}: {2}", a, b, a.Equals (b)); // The Type objects

Comments
  • Can you provide some more details, regarding the two classes. What are the attributes you're referring to?
  • Any attribute. I don't want to describe all the attributes because the solution needs to be generic.
  • I think now you should be able to accept your answer ;-)
  • As explained, my classes are generated code, and also I have a lot of attributes so I don't want to write the equal method.