Note that your code mixes getters and fields and throws an NPE.
Do you really need a bunch of methods or would a single, more general method do?
I'd strongly prefer the latter as for a bunch of methods to be useful, you'd need a bunch of callers and the code bloat would proliferate.
For this, you can use reflection or annotation processing. Reflection has some runtime overhead (not as bad as it used to), but it can access private members (unless forbidden by a security manager).
Something like the following should do
public static ImmutableSet<String> differingFields(Object o1, Object o2) throws IllegalAccessException {
checkNotNull(o1);
checkNotNull(o2);
checkArgument(o1.getClass() != o2.getClass());
ImmutableSet.Builder<String> result = ImmutableSet.builder();
for (Field f : o1.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (!Objects.equals(f.get(o1), f.get(o2))) {
result.add(f.getName());
}
}
return result.build();
}
It uses Guava, 'cause I prefer immutable results, but it's not needed. The inefficiencies come from autoboxing and reflective access and are most probably acceptable.
It only works when instances of exactly the same class are passed in. It ignores inherited fields. This is easily fixable.
Instead of just the field names, you could return Guava's MapDifference
or alike. Instead of implementing differingFields
, you could convert your objects to maps and work on them.