For two arbitrary objects, you can reflectively iterate over the fields in one of the objects to see which fields the objects both have, 1:1. You can then compare these fields.
For the quick solution, check below.
Here's a really big and possibly annoying example:
class Test {
public static Field getFieldSafely(String fieldName, Object object) {
Field[] fields = object.getClass().getFields();
for (Field f : fields)
if (f.getName().equals(fieldName))
return f;
return null;
}
public static boolean equal(Object first, Object other) {
for (Field f : first.getClass().getFields()) {
String fieldName = f.getName();
Field otherField = getFieldSafely(fieldName, other);
if (otherField != null)
try {
if (!f.get(first).equals(otherField.get(other)))
return false;
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle(5, 10), vehicle2 = new Vehicle(5, 10), vehicle3 = new Vehicle(5, 20);
Box box1 = new Box(5, 10), box2 = new Box(100, 200);
System.out.println(equal(vehicle1, vehicle2));// True
System.out.println(equal(vehicle2, vehicle3));// False
System.out.println(equal(vehicle1, vehicle3));// False
System.out.println(equal(box1, box2));// False
System.out.println(equal(vehicle1, box1));// True
}
}
class Box {
public int width, height;
public Box(int width, int height) {
this.width = width;
this.height = height;
}
}
class Vehicle {
public int width, height, weight;
public Vehicle(int int1, int int2) {
this.width = int1;
this.height = int2;
}
}
The most important methods are in the class Test
. The method, equal(...)
, takes in two objects. It then checks if each field in the first object is contained in the second object. For each field it finds in the first object, that has the same name as a field in the second object, the fields are checked for equality. If all the fields found in both objects are equal, the method returns true
. Otherwise, it returns false
.
Here are the important methods. You can modify them as you see fit to meet your needs.
getFieldSafely(...)
simply returns null if a field with the given name isn't found in the given object. Otherwise, it returns the field.
public static Field getFieldSafely(String fieldName, Object object) {
Field[] fields = object.getClass().getFields();
for (Field f : fields)
if (f.getName().equals(fieldName))
return f;
return null;
}
public static boolean equal(Object first, Object other) {
for (Field f : first.getClass().getFields()) {
String fieldName = f.getName();
Field otherField = getFieldSafely(fieldName, other);
if (otherField != null)
try {
if (!f.get(first).equals(otherField.get(other)))
return false;
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
return true;
}
Good luck. :)