Overloading - how do I avoid instanceof?

I am looking for a way to chose between overloaded methods without using specific casts.
The following code tries to explain my problem:
public class Overloading {
     public static void main(String[] args){
          new Overloading();
     public Overloading(){
          Animal macavity = new Cat();
          classify(macavity); // macavity is not classified as a cat
          // this is what I want to avoid having to do
          if(macavity instanceof Cat)
               classify((Cat)macavity);
     private void classify(Animal animal){
          System.out.println("Just an animal.");
     private void classify(Cat cat){
          System.out.println("A cat!");
     class Animal{}     
     class Cat extends Animal{}
}In the project I'm working has sanctioned that "Animals" cannot be allowed to classify themselves; they must be classified "from the outside" (not my rules).
In the code I use instanceof to force use of the correct overload, but since there might be many animals this checking quickly becomes cumbersome!
Is there any way I can cast an animal into its instantiation type without using instanceof?

There's not a whole lot you can do as Java is not a dynamically bound (ie. at runtime) language. Java always uses the variable type at compile-time to decide which method is being called. 2 suggestions:
1). You use reflection to be terribly clever at runtime and decide which method should be called.eg.
    Method m = Overloading.class.getDeclaredMethod("classify", macavity.getClass());
    m.setAccessible(true);
    m.invoke(macavity);This is almost certainly a very bad idea.
2). Use some kind of handler-chain to classify and pass the animal along the chain until it is handled. You don't avoid the instanceof mess, but at least you don't have a huge if-else block.
    public class ClassifierChain
        public static interface Classifier {
            /** Return true if the implementation can classify the Animal */
            boolean classify(Animal a);
        public void classify(List<ClassifierChain.Classifier> classifiers, Animal a) {
            for (ClassifierChain.Classifier classifier : classifiers) {
                if (classifier.classify(a)) break;
    public class CatClassifier implements ClassifierChain.Classifier {
        public boolean classify(Animal a) {
            if (a instanceof Cat) {
                // ... do something with a cat
               return true;
            return false;
    }Rubbish design, but you get the idea. Having said this, the previous post makes a lot of sense; in most cases it makes sense to keep your type-specific code bound closely to the type (ie. as a method on it). Obviously there are plenty of examples where this is a bad idea (eg. coupling UI-code to domain object classes).

Similar Messages

  • Cache engine overloads, how to.....

    i've cisco cache engine 505 attached with cisco 2611 router. Now whenever i reload my cache engine it performs its job for 5 minutes after that it overloads and cannnot perform its job and cache engine changes its state to bypass mode.
    What could be the factors that causes this problem?
    How can i avoid this problem.
    this could be memory issue? if yes then which memory.hardisk or RAM or else?
    pls reply me as soon as possible.

    The ICAP daemon on the Content Engine continues to send updates (from the HTTP response) to the ICAP server, and it overloads the cache engine

  • Multiple users on a itunes account how do I avoid eveyone getting my information on icloud

    I have multiple users on our itunes account. If I switch to mountain lion and utilize icloud how do I avoid the other phones my kids and husband from getting all my stuff on their phones. I am the primary account holder when we first upgraded the phones all my contacts went to their phones and wiped out all of theirs it was a night mare so we just shut it off. It sounds like a cool idea but I dont want to mess up their contacts and information.

    You can keep everyone on your iTunes account all you have to do is have everyone create there own iCloud account. Me, my wife, and my son all have our own iCloud for our own use. I have my 3 devices linked to mine, my son has 2 linked to his and my wife has 2 also. For some reason by default the iDevice will ask you to use your iTunes account but you don't have to. You can create it right from the device itself if you want a @me account which is the way to go IMO. you can also go to iCloud.com and create it there too. We have a total of 8 devices linked to one iTunes account for purchases and everything works like a champ. Hope this helps.

  • Hi. I purchased a new ipad mini and my brother already has iphone 4,so how can i avoid sharing the same contents that are on his phone? Will creating an other apple id help us in seperating our facetime and icloud accounts as we share our laptop to sync ?

    Hi. I purchased a new ipad mini and my brother already has iphone 4,so how can i avoid sharing the same contents that are on his phone? Will creating an other apple id help us in seperating our facetime and icloud accounts as we share our laptop to sync ?

    Have a read here...
    https://discussions.apple.com/message/18409815?ac_cid=ha
    And See Here...
    How to Use Multiple iDevices with One Computer

  • I download apps directly to my iphone.  When I sync with my laptop, how do I avoid having sync delete apps, photos, songs downloaded on my iphone?

    I download apps directly to my iphone.  When I sync with my laptop, how do I avoid having sync delete apps, photos/vdeos, songs downloaded on my iphone?

    If you are syncing to the same computer that you always sync to, and have each of the items in itunes that you want synced then you shouldnt have an issue. The only way you would have an app come off your phone is if you uncheck that app from syncing in th apps location in itunes.

  • How can i avoid restarting tomcat server when servlet is modified?

    please advice me that how can i avoid restarting the tomcat server, whenever a servlet file is modified in my application. is their any way ?

    No probs. Here's how I do things...
    1. Install tomcat as normal (e.g. I install to C:\Apps\jakarta-tomcat-5.5.4)
    2. Create a webapps directory in your eclipse project with the following directory structure
    MyEclipseProject
       - src
       - conf
       - webapps
          - MyApplication
             - META-INF
             - WEB-INF
                - classes
                - lib
                - pages3. Set the project's output folder (e.g. bin folder) to webapps/MyApplication/WEB-INF/classes
    4. Put all your jar files in the lib directory
    5. Put JSPs / HTML in the pages directory (you may also want to create additional directories for TLDs, config files etc)
    6. Ensure your web.xml is in the WEB-INF directory
    7. Although it isn't essential I create a context.xml file and store it in META-INF, e.g.
    <Context reloadable="true">
        <!-- Default set of monitored resources -->
         <WatchedResource>WEB-INF/web.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/struts-config.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/tiles-defs.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/validation.xml</WatchedResource>     
    </Context>I use this to set monitored resources that will trigger an automatic appliation reload and to configure JAAS (not shown). See the Tomcat documentation for additional information.
    8. In the 'conf' directory I create a server.xml file used to configure Tomcat (you can copy the one from your <TOMCAT_HOME>/conf/server.xml).
    After copying the file change appBase attribute in the host element to be the full path to the webapps directory. You can also change the HTTP and HTTPS ports if you wish
    9. Download and install the Tomcat Launcher plugin from Sysdeo.
    10. In Eclipse's Preferences menu you will see a new entry for Tomcat. Click this then
    a. Set your Tomcat Version
    b. Set your Tomcat Home
    c. Set "Context declaration mode" to server.xml
    d. Set the configuration file to the full path to your server.xml file created in step 8
    On the "Advanced " sub page select all relevant projects to add to the Tomcat classpath
    On the "JVM Settings" page add all the jars in your WEB-INF lib directory to the class path
    On the "Source Path" page select all relevant projects
    Now if you start Tomcat using the Tomcat icon, you will be able to remote debug your application. If you change web.xml (or any other file in your context.xml watched resources) it will automatically reload. Any changes to JSPs will automatically be picked up (providing your tell your browser not to use the page in cache - e.g. CTRL+F5 in IE)
    There are some limitations that I'm still working on however. Primarily that I haven't included the Tomcat Manager application in my webapps directory, so Sysdeo cannot perform a reload. This means that if I change a source file, and eclipse auotmatically rebuilds, Tomcat doesn't pick up the change unless I either change a watched resource file (e.g. web.xml) or stop and restart Tomcat.
    There's no reason why this can't be fixed, I just haven't got round to it yet.
    I'm sure there are lots of other (probably better) ways of achieving the same thing. This was the first method I tried and it worked, so I stuck with it. I'm not a Tomcat config guru and I'm sure other forum users could provide some improvements should they wish.
    Post if you get into trouble, however I won't be able to respond until next week.
    Cheers,
    Steve

  • How do I avoid re-entrant problems in Oracle JVM

    I have a Java program called LanguageFunctions. This Java program has several methods that translate the data within a String or CLOB. I want to use this Java program as a stored procedure, and specifically the methods as Oracle functions. I want this function to be accessed simultaneously without either re-entrant, lock or performance concerns. I want to be able to use the functions something like this:
    SELECT TO_CHINESE(VARCHARCOL1) FROM DUAL;
    SELECT TO_FINISH(CLOBCOL1) FROM DUAL;
    I am having trouble understanding the Java requirements for these methods. I am greatly concerned about multi-user usage and issues with re-entrant code. Does this have to be a static class? If not, how when and where does it get instantiated (I hope not for every invocation of the function)? How to I avoid having one user accidentally changing the data within the method when executed in parallel?
    BTW: I have successfully moved these into the Oracle JVM, and executed them as a single user. My main concern is the re-entrant code issues.
    Thanks

    Thanks for the reply, I meant no disrespect, I was just trying to be a little funny...
    I did read that any method that you want to use as an Oracle function must be static. So I understand that as a given. However, the class I am converting uses static Class variables. You can see this in the example as the textOut variable.
    When two users are accessing this function in parallel, I could see the following series of events ocurring, and it is my concern. There is only one textOut, and I believe it can be modifed by both functions simultanesouly with unexpected results. I'm assuming my for loop is set to x < 2.
    SessionA issues: SELECT TO_DANISH('HELLO') FROM DUAL;
       A --> textOut = ""
       A --> textOut = "HELLO"
       A --> textOut = "HELLOxy"
       A --> textOut = "HELLOxyxy"
    SessionB issues: SELECT TO_DANISH('GOODBYE') FROM DUAL;
       B --> textOut = ""
       A --> textOut = "xy"
       B --> textOut = "GOODBYE"
       A --> textOut = "GOODBYExy"
    Session A returns: "GOODBYExy"     (expected "HELLOxyxy")
       B --> textOut = "GOODBYExyxy"
       B --> textOut = "GOODBYExyxyxy"
    Session B returns: "GOODBYExyxyxy" (expected "GOODBYExyxy")I'm I correct in my assumption that this is an issue? If so, what type of programm architecture would be best to use to manage this? I've tried to provide a simple working example of the issue, but the program that I'm working on actually alters the contents of textOut (as a static Class variable) in 5 or 6 different methods, including one method using recursion. I know I may need to make changes to the program architecture to make it work properly in a multi-user environment as an Oracle function. I'm just a little confused on what the appropriate architecture is. Once again any help is appreciated!
    Joel

  • I have made a book of my I Photo pictures. In certain layouts there is a textframe. How can I avoid the frame becoming visible in the print if I don't want to write anything? Should I just leave it or should I delete the text "Write your text here" ?

    I have made a book of my iPhoto pictures. In certain layouts there is a text frame. How can I avoid the frame becoming visible in the print if I don't want to write anything?  Should I just leave it untouched or should I delete the instructing text "Write your text here"?

    Most pages have layouts for pictures only or pictures with text boxes. Either select the same layout for that page but the one without the text box or put a space in the text box.
    Putting a space in the text box will avoid getting the warning when ordering that there's an unfilled text box in the book. The box will not be visible in the final product.  You can and should check the book before ordering by previewing it as described in this Apple document: iPhoto '11: Preview a book, card, or calendar before you order or print it
    Happy Holidays

  • HT1766 Now, I understand how the backup and restore the backup functions. However, if I don't want to transfer the music that I have on iTunes to my phone, how do I avoid it? How do I not transfer the music or take it out of my iPhone if it is already the

    Now, I understand how the backup and restore the backup features function. However, if I don't want to transfer the music that I have on iTunes to my phone, how do I avoid it? How do I not transfer the music or take it out of my iPhone if it is already there? I really do not want any music on my iPhone because I have an iPod for that. Thanks. Hope someone can help.

    When you connect your phone and start iTunes on the left side you will see your phone listed under devices.Click on te icon next to it that looks like a battery. Click on the music button at the top and uncheck the sync music box.

  • How do I avoid duplicates after signing back in to my current iCloud account on my iPad?

    I had to delete my newer iCloud account and sign in to the App store with my old AppleID to download missing apps on my first generation iPad. I did not delete Contacts or Calendar entries when I deleted the newer account so the data is still on my iPad. After I updated the apps I deleted the old account and signed on again with my newer account. I did not allow any data to merge when I signed in with either account. My question is: if I turn on Contacts and Calendar will the data duplicate? If so how can I avoid that happening? (I hope I explained this clearly enough)

    Having just changed my Apple ID to separate myself from my son who was sharing my ID I can tell you how to handle this in IOS7.  I went to the Apple web site and established my new ID.
    I followed the advice on this support page to change my Apple ID  Change your Apple ID - Apple Support
    I then followed the advice on this page to update the ID on my device Sign in with a different Apple ID on your iPhone, iPad, or iPod touch - Apple Support
    IMPORTANT!!!! When you delete your iCloud for your old Apple ID off your phone you will lose all your documents that are in the cloud but not your contacts that are out in the cloud.  Also, before following the directions on the"Sign in with a Different Account" page to delete the iCloud Apple ID first turn off iCloud sync on each item individually.  When you turn off the sync it will ask you if you want to keep the data on your phone.  Yes you do want this.  After turning off sync individually Delete the iCloud account for the old Apple ID.  Then when you then sign into iCloud with your new Apple ID select the Merge option and it will upload all your contacts and data to the iCloud account for your new Apple ID.
    If you simply Delete your iCloud account it will delete all your contacts off your phone.  If you delete iCloud without first turning sync off Contacts and your contacts are then deleted off your phone, don't worry.  Simply log back into iCloud with your old account and your contacts will be restored.  Then you can turn off the sync on all items, Delete the old account from iCloud, sign in with the new apple Id, select Merge iPhone data.  So it puts your contacts and data from your phone into your new iCloud account.

  • I changed my password to use migration to transfer files from a G4 to a new macbook pro but now I have to sign in every time. How do I avoid the sign in?

    I changed my password to use migration to transfer files from a G4 to a new macbook pro but now I have to sign in every time. How do I avoid the sign in?

    I clicked on keychain access but getting a warning that it quit unexpectedly and it won't reopen.

  • How can I avoid (on a mac) getting called on Skype...

    How can I avoid (on a mac) getting called on Skype when I'm not signed in?
    It's really annoying.
    I'm not sure if it's supposed to be that way, but suddenly I get the skype-calling-sound, and I have to log into the skype app to abort the call. The persistent calling bastards kept on calling after I aborted the call and left the app, so I ended up muting my speakers for a while. It really shouldn't have to be this troublesome.

    That's like asking how many cows can I get into a field.  It depends on the size of the field, size of the cows, the terrain of the field, etc.  We could use a bit more information on what you're trying to accommplish:
    1 - where are the photos being downloaded from.
    2 - how big are the photos?
    3 - where are you going to put the photos, i.e. into folders, into an iPhoto library?
    4 - how big is the hard drive in the Mac Pro and how much free space do you have on it?
    etc., etc, etc......

  • I got my ipod, and my wife, her iphone. I downloaded an app and use it in my itouch, but when my wife download it in her iphone, and the phone ask her to update it, it asks for my apple ID, but she has her own apple ID, how do we avoid this?

    I got my ipod, and my wife, her iphone. I downloaded an app and use it in my itouch, but when my wife download it in her iphone, and the phone ask her to update it, it asks for my apple ID, but she has her own apple ID, how do we avoid this?

    Hi peacemakerco,
    Thanks for visiting Apple Support Communities.
    You can use the steps in this article to sign in on the iPhone with the right Apple ID:
    iOS: Changing the signed-in iTunes Store Apple ID account
    http://support.apple.com/kb/ht1311
    Best,
    Jeremy

  • How can i avoid displaying runtime error in intractive report

    hi gurus
    my question is, in interactive report when i reach 20th secondary list after that am getting runtime error when i click again. So i wanted to know how can i avoid that run time error.
    regars
    imran

    Hi Imran,
    Basically we can have one basic list and 20 interactive lists.
    Once when we reached to 20th list then it goes to shortdump.
    So, inorder to avoid that we can modify the system field
    SY-LSIND.
    Just see this example and try this. I hope this will be useful for you.
    REPORT  ZSAMPLE1111.
    data: begin of itab occurs 0,
            matnr like mara-matnr,
            mtart like mara-mtart,
            mbrsh like mara-mbrsh,
            end of itab.
    data: begin of jtab occurs 0,
          maktx like makt-maktx,
          spras like makt-spras,
          end of jtab.
    select matnr mtart mbrsh into table itab from mara up to 10 rows.
    loop at itab.
    write:/ itab-matnr, itab-mtart, itab-mbrsh.
    hide itab-matnr.
    endloop.
    at line-selection.
    select maktx spras into table jtab from makt where spras = 'EN' .
    case sy-lsind.
    when '1'.
    loop at jtab.
    write:/ jtab-maktx, jtab-spras.
    endloop.
    when '20'.             * changes see here.
    sy-lsind = 1.
    when others .
    write:/ 'name',sy-lsind.
    endcase.
    I hope this will be helpful for you.
    <REMOVED BY MODERATOR>
    Cheers,
    Swamy kunche
    Edited by: Alvaro Tejada Galindo on Apr 15, 2008 4:01 PM

  • How do I avoid the recipient of my Indesign PDF receiving a security warning when clicking on links?

    I create PDF's out of Indesign to send to new clients. They contain links to external websites. They do not contain any javascript or videos or hidden links. If the PDF is opened in Adobe Reader, when the recipient clicks on a hyperlink in my PDF they get a security warning asking if they trust the site. How can I avoid the recipient receiving this Security Warning as it would scare people into thinking I had sent them something malicious when I haven't?

    You cannot avoid it, that's part of the PDF security system to make the user aware that he is entering non-trusted area, as it is with every web page when it is opened the first time in Reader or Acrobat on this computer. ThatÄs an unchageable fact. You have to live with it.

Maybe you are looking for