I see are two ways, the preferred, Java-typical way using the equals()
method, and a fragile, reflection-based way.
Using equals()
All decent Java classes should implement the equals()
method, meant to compare two objects for having semantically the same contents. I guess that definition matches your requirement "the same values in their parameters" (it's not literally what you ask for, but for good reason - see below). Of course, this relies on the relevant classes having a proper equals() implementation, or you being able to add one to the relevant classes. Go that way if possible.
Using reflection
Disclaimer: Avoid that way if possible.
Java allows you to find the fields that a given class has, and to read out the value of such a field for a given instance. So you can:
- Find the class of the first object.
- Compare to the class of the second object, returning false if different.
- Find the fields of the class.
- Iterate over the fields, getting the field values of both objects.
- Compare the field values (using the equals() method? Recursively using your reflection-based comparison? - you decide...).
Why a class-specific equals() method is better than a blind field-values comparison
Not all fields are created equal. Often, a class has internal fields that have nothing to do with an object property you'd want to compare when asking for property equivalence. Examples:
- To make some computations faster, the instance caches some dependent data. Having the cache filled or empty technically is a different field value, but has no semantic meaning.
- The instance maintains some
lastAccess
date. Technically, you'll get different values most of the time, but that doesn't mean that some relevant object property is different.
Blindly comparing object fields will always fall into the trap of comparing these fields as well, although they don't have that semantic meaning you'd expect.
Only the class itself knows which fields to usefully compare and which ones not. And that's why every class should have its own equals()
method, and why that should be used for contents comparison.