Note that there are some explanatory texts on larger screens.

plurals
  1. POEffective Use of Java Reflection - is this a hack, or is this standard practice?
    text
    copied!<p>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.</p> <pre><code>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 &amp;&amp; method.getName().startsWith( "get" ) &amp;&amp; !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 &amp;&amp; methodValue != null &amp;&amp; !arcMethodValue.equals( methodValue ) ) { return false; } else { if ( arcMethodValue == null &amp;&amp; methodValue != null || methodValue == null &amp;&amp; arcMethodValue != null ) { return false; } } } } return true; } </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload