Skip to content

Java reflection vs Ruby respond_to?

Saturday, 8 October 2005  |  Richard Dale

I've recently been making some rubbish attempts at fixing a bug in the QtJava bindings. The problem is here in bug #112409, it meant that an event handler method in QtJava could only be a direct subclass of a QtJava widget, like QWidget or whatever and not a sub class of a sub class of QWidget and so on. To fix it involved using java reflection to look for any overriden event methods in the java superclasses by writing a loop to go up the class heirarchy. Please laugh at my comments as I continually screw up on the commit :).

Here is how you do it in Ruby:

instance.respond_to? :mouseReleaseEvent

Um, not much to be said really..

And here is my effort in Java after 4 tries getting it wrong:

Class targetClass = onThis.getClass();

do { try { method = targetClass.getDeclaredMethod(methodName, parameterType); method.setAccessible(true); break; } catch (NoSuchMethodException e1) { }

    targetClass = targetClass.getSuperclass();

} while (targetClass != null);

if (targetClass == null) { return false; }

This disadvantage of the Ruby approach is that it works first time without you having to think about it. Whereas the Java one allows you to display skills such as writing twisty loops with exception handling as in the above code, and looking like a loser on kde-commits :)