Before I get into the details on the solution I came up with to deal with this scenario I should probably explain why I want this. The goal is to have a fairly generalize broadcaster / listener setup where a thread can subscribe to another thread and anytime anything interesting happens in the subscribed thread it will broadcast a message out to all it's listeners. Sometimes, the listener will care about the particular message and want to enter some handling function when it receives the message but other times the listener doesn't care about a particular method. Also, if a new method is implemented in the broadcaster I don't want all listeners to break until I get around to implementing a processing function.
Enter Java hacks.
The code is written for Android, but those of you working with Vanilla Java can think of a Bundle as a Serialized object. The same code could be used for serialized objects instead of bundled objects with minimal changes. We start off by figuring out the name of the class that was serialized. In the case of my bundled object the class name is just a string inside the bundle. For a serialized object you would deserialize it and call object.getClass().getClassName(). Once we have the class name we then want to instantiate one of those classes on the receiving side. For a bundle, this means calling a custom constructor that takes the bundle as a parameter and rebuilds the class from that. For a serialized object you don't have to do anything as the serialization system takes care of reconstruction for you.
Now for the interesting part, taking an unknown object (as far as the source code is concerned) and entering into some custom handling for whatever type of object it really is. To do this the receiver has an overloaded Process function for each of the messages that he wants to handle. We then search the receiving class for a Process function that takes our message object as a parameter. If it doesn't find it an exception will be thrown which can be caught and the packet dropped if you like, or perhaps some kind of error to the developer. If it is found that Process function is then called with the object passed in as a parameter which now takes us back into compile-time checked land where we no longer have to deal with generic "objects".
And here is the code for using Serializables.
No comments:
Post a Comment