This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a scenario where in I would be receiving java classes from an external system. There are 30 different classes. Depending on the incoming class I have to tread a separate path of execution. So what would be the best way to determine class information (i.e. class name) Should I be storing all the possible class details in a Collection class & then match each with the incoming class.
Do post what would be the best way for im[plementing the same
Do these classes have anything in common (such as extending a common base class, implementing an interface or all providing a specific method?) Do you know in advance what classes might arrive, or do you have to guess what to do from a potentially unknown class name?
Thanks for your response. Yes all these class will be extending a common abstract class & there is a base implementation of a method called toXML() which I will have to override in all the derived classes. Yes I would be knowing in advance that the classes that would arrive would be 1 out of the possible 30 classes.
Actually there is a listener which is registered with Vignette content management system which consumes events. Now these events can be of different types like createPerson or deleteDepartment or modifyHistory . So here Person, Department & History are the classes which will be received. & I have to determine them at runtime & retrieve the xml from the toXML() method which would return String and then make the appropriate changes & send it to another content management system
Joined: Jan 29, 2003
It's good news that all the classes extend a common base class or implement a common interface. Then polymorphism lets you call the toXML() method without even knowing what kind of object you really have.
Let's say Vignette wasn't so kind as to make a common interface. I've been stuck in situations where the object coming in has no useful methods or common base or anything remotely good. I made a map of classnames to handlers:
That factory is just a glorified HashMap that can deal with objects that don't have defined handlers, maybe by throwing an exception or something.
In your case, since you have to do additional custom processing for each type, make the handler do more:
Either of these techniques is neat because we can add new event objects without touching this particular code. Vignette might send us a new implementation of KnowsHowToMakeXML or our map might have a new handler from configuration. Every class you don't have to modify is one less chance to break something. [ November 03, 2006: Message edited by: Stan James ]
Joined: Oct 23, 2003
Hi Stan James,
Thanks a lot for the ellaborate explanation. That was indeed very helpful & gives us a good direction to proceed