This discussion is archived
1 Reply Latest reply: Sep 13, 2013 3:27 PM by rp0428 RSS

best way to call methods on similar objects without an interface

malky Explorer
Currently Being Moderated

Hi,

I have two objects that i need to iterate, they both have the same method i need to call during iteration, but those two objects are from different libraries and i cannot change them to add them as implement interface...

 

   for (Iterator it = documents.iterator(); it.hasNext();) {
           Document1 document = (Document1) it.next();
           document.getName();
       }

 

But I can also get a documents's collection where the object is Document2 and not Document1 that also has getName(), what's the best way to implement this? I mean i know i can just add if conditions to say if (instanceof) do this or that.. but I don't think this is good as everytime there's a new type of doc i'd have to add one more...

 

Any suggestions?

 

Thanks,

  • 1. Re: best way to call methods on similar objects without an interface
    rp0428 Guru
    Currently Being Moderated
    I have two objects that i need to iterate, they both have the same method i need to call during iteration, but those two objects are from different libraries and i cannot change them to add them as implement interface...

    You already know what you need to do. You just don't want to do it.

     

    You can't treat two (or more) instances the same if they aren't the same. Here are three methods:

     

    1. Add code (like you propose) to determine which type you have

     

    2. Create your own classes that extend those classes and have your own class implement your own interface that has the 'getName' method. When you create instances of your own class the constructor can have code that determines which type you have and then use the appropriate 'getName' method. Your app code would use your own classes instead of the ones from the libraries

     

    3. Use reflection to call the 'getName' method.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points