Hey, long time listener first time caller, and I'm asking a question related to Java reflection, and how easy it lends itself to apparently ugly coding. The following method attempts to take two similar objects (one object having all of the fields of the other object, and then some) and compare the two of them for equality. It will (allegedly) return true if the getters that the objects share are equal, and will return false if they are not equal.
public boolean validateArchive( Object record, Object arcRecord ) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
log.debug( record.getClass().toString() );
Object methodValue;
Object arcMethodValue;
for ( Method method : record.getClass().getMethods() )
{
if ( method.getTypeParameters().length == 0 && method.getName().startsWith( "get" ) && !method.getName().startsWith( "getClass" ) )
{
methodValue = method.invoke( record );
arcMethodValue = arcRecord.getClass().getMethod( method.getName() ).invoke( arcRecord );
log.debug( "Method name: " + method.getName() );
log.debug( "Archive value: " + arcMethodValue );
log.debug( "Object value: " + methodValue );
if ( arcMethodValue != null && methodValue != null && !arcMethodValue.equals( methodValue ) )
{
return false;
}
else
{
if ( arcMethodValue == null && methodValue != null || methodValue == null && arcMethodValue != null )
{
return false;
}
}
}
}
return true;
}
This method does what I expect it to do in the unit tests, but it looks ugly, and feels wrong (I'm particularly not a fan of the nested 'if'). I was just hoping for some pointers on how to do this more effectively/efficiently. If I've broken some kind of posting rule, feel free to correct me, I am eager to learn, etc.