[EXT] How to convert objects up and down a class hierarchy in Java

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

[EXT] How to convert objects up and down a class hierarchy in Java

I am facing a behavior that I can't quite understand and although I have worked around it by duplicating code, I am curious as to the reasons of this behavior.
In the main dialog of an extension that I have written (in Java), I tie several controls to the same event handler (whether the event is from the keyboard or the mouse). In some handlers, I happen to accomplish different actions depending on the source of the event: a button labeled "Close" will trigger a call to the 'close' method of a worker object, "Tag" will call another method, etc.
Identifying the source control was done by a method – with this signature: public static String getActionEventSourceName(ActionEvent event) – which gets me the name of the control.

Up until today, I used to need which control was a source only for ActionEvent objects, triggered from buttons. Starting from today, I also need this identification of the source for KeyEvent objects.The hierarchy of event classes involved is this:  
   - com.sun.star.lang.EventObject > com.sun.awt.ActionEvent
   - com.sun.star.lang.EventObject > com.sun.awt.InputEvent > com.sun.star.awt.KeyEvent

Using this hierarchy information, I thought that instead of making the _event_ parameter an ActionEvent, I could just go higher in the hierarchy and upcast the event to an EventObject; that way, I could use a single method instead of duplicating the code for ActionEvent and KeyEvent.
The problem is that when the parameter type is EventObject, the instruction below stops the execution flow (meaning that the target method is not called at all) and I get no errors or warnings of any sorts in the NetBeans debugger output:String sName = EventUtils.getActionEventSourceName(actionEvent);

Given that an ActionEvent object is an EventObject, why does changing the type of the argument in getActionEventSourceName cause the call to fail, silently? I'm suspecting that downcasting and upcasting don't work as I think they do.
If someone could shed some light on this mystery, I'd be grateful. Thank you.