Newbie question: ""dynamic"" casting

Hello all,
<br>
I have a quite newbie question. I have this class hierarcy:
<br>
A
|_A1
|_A2
|_A3
|_A4
|_A5
|_.....
<br>
in some part of my code I have this:
<br><br>
if (object1 instanceof A){
if (object1 instanceof A1)      {A1   object2 = (A1) e;}
          if (object1 instanceof A2)      {A2   object2 = (A2) e;}
          if (object1 instanceof A3)      {A3   object2 = (A3) e;}
          if (object1 instanceof A4)      {A4   object2 = (A4) e;}
          if (object1 instanceof A5)      {A5   object2 = (A5) e;}
object2.callMethod();
<br><br>
Is there any way to do this type of casting just in one line? I mean, I just want to cast object1 to the class it is instanceof. If it is instance of A1, I want to be casted to A1, if it is A2 to A2, etc...
<br><br>
Thanks you in advance.

kamikaze04 wrote:
In fact I know what object1 is on execution time,Which doesn't help your compiler at all, when it's task to link and verify method calls.
because the code posted at the top is working well, i just want to avoid repeating that if's for all the new classes Ax I will create. Big "code smell" here.
In other words if i had from A1 to A200 i dont want to have 200 if's to cast it to the class it is and then execute it's method.You could call the method "doMagic()" and make it abstract in A. Then you can implement it in all Ax classes and would never have to worry about casting in the first place, because A.doMagic() would automagically do the right thing. Polymorphism.

Similar Messages

  • Dynamic cast at runtime (Here we go again! )

    Hy folks,
    today I read so many entries about dynamic casting. But no one maps to my problem. For a lot of them individual alternatives were found. And so I hope...
    Ok, what's my problem?
    here simplified:
    I have a HashMap with couples of SwingComponents and StringArray[3].
    The SwingComponents are stored as Objects (they are all JComponents).
    The StringArray comprised "the exact ClassName" (like "JButton" or "JPanel"),
    "the method, who would be called" (like "addItemListener")
    and "the ListenerName" (like "MouseMotionListener" or "ActionListener")
    At compiletime I don't know, what JCommponent gets which Listener.
    So a JPanel could add an ItemListener, another JPanel could add
    a MouseListener and an ActionListener.
    I get the description of the GUI not until runtime.
    The 'instanceof'-resolution is not acceptable, because there are above 50 listener. If I write such a class, I would write weeks for it, and it will be enormous.
    Now, my question
    I get the class of the Listenertype by
    Class c=Class.forName(stringArray[2]);
    and the method I'll call
    java.lang.reflect.Method method=component.getClass().getDeclaredMethod(s[1],classArrayOfTheParameter[]); //the parameter is not important here
    And I have a class, who implements all required ListenerInterfaces: EHP
    Now I wish something like this
    method.invoke((JPanel)jcomponent,(c)EHP);
    Is there anybode, who can give me an alternative resolution
    without instanceof or switch-case ?
    Greatings egosum

    I see, your right. Thanks. This problem is been solved.
    But a second problem is, that jcomponent can be every Swing-Object.
    I get the swing-component as Object from the HashMap . And I know
    what it is exactly by a String.
    What I need here is
    method.invoke(("SwingType")swingcomponentObject,Object[] args);
    I know, that this doesn't exist. Here my next question
    Can I take an other structure than HashMap, where the return value
    is a safety type (and not an Object). Or there are some other hints
    about similar problems and there resolutions?
    I don't like to write 50 (or even more than 50) "instanceOf"-instructions or "equal"-queries. And I'm not really interested in the whole set of java swing elements existing.
    I appreciate all the help I can get.
    With regards egosum

  • Multiple version of JRE in company..How to manage? (newbie question)

    Greetings..this is a newbie question
    We have 48 versions of JRE running in on XP IE6 in our company.
    Some version beat up other JAVA applications.
    It's a mess.
    How can anyone manage this many versions?
    Can we consolidate down to a few versions?
    I saw some posts on changing the JRE dynamically or perhaps using a wrapper with a product from "sourceforge".
    Are these viable?
    Thanks in advance

    We have 48 versions of JRE running in on XP IE6 in
    our company.
    Some version beat up other JAVA applications.
    It's a mess.can you elaborate on how some versions "beat up" other apps?
    How can anyone manage this many versions?you don't, each computer should periodically upgrade (IMO) but you shouldn't care. if you do, tell your users to load the latest version
    Can we consolidate down to a few versions?sure
    I saw some posts on changing the JRE dynamically or
    perhaps using a wrapper with a product from
    "sourceforge".
    Are these viable?i have no idea what this is, but I have doubts about your problem, if it exists at all

  • Private inheritance and dynamic cast issue

    Hello. I am hitting a problem combining private inheritance and dynamic casting, using Sun Studio 12 (Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25):
    I have three related classes. Let's call them:
    Handle: The basic Handle class.
    DspHandle. Handle implementation, able to add itself to a Receiver.
    IODriver. Implemented in terms of DspHandle, It is the actually instantiated object.
    Consider the following code. Sorry, but I've tried my best trying to minimize it:
    #include <iostream>
    using namespace std;
    class Handle {
    public:
    virtual ~Handle() {};
    class Receiver {
    public:
    void add(Handle &a);
    class DspHandle : public Handle {
    public:
    virtual ~DspHandle() {};
    void run(Receiver &recv);
    class IODriver : private DspHandle {
    public:
    void start(Receiver &recv) {
    DspHandle::run(recv);
    void DspHandle::run(Receiver &recv) {
    cout << "Calling Receiver::add(" << typeid(this).name() << ")" << endl;
    recv.add(*this);
    void Receiver::add(Handle &a) {
    cout << "Called Receiver::add(" << typeid(&a).name() << ")" << endl;
    DspHandle d = dynamic_cast<DspHandle>(&a);
    cout << "a= " << &a << ", d=" << d << endl;
    int main(int argc, char *argv[]) {
    Receiver recv;
    IODriver c;
    c.start(recv);
    Compiling and running this code with Sun Studio 12:
    CC -o test test.cc
    ./test
    Calling Receiver::add(DspHandle*)
    Called Receiver::add(Handle*)
    a= ffbffd54, d=0
    The dynamic cast in Receiver::add, trying to downcast Handle to DspHandle, fails.
    This same code works, for example with GNU g++ 4.1.3:
    Calling Receiver::add(P9DspHandle)
    Called Receiver::add(P6Handle)
    a= 0xbfe9c898, d=0xbfe9c898
    What is the reason of the dynamic_cast being rejected. Since the pointer is actually a DspHandle* , even when it is part of a private class, shouldn't it be downcastable to DspHandle? I think that perhaps the pointer should be rejected by Receiver::add(Handle &a) as it could be seen as a IODriver, that can't be converted to its private base. But since it's accepted, shouldn't the dynamic_cast work?
    Changing the inheritance of IODriver to public instead of private avoids the error, but it's not an option in my design.
    So, questions: Why is it failing? Any workarround?
    Best wishes.
    Manuel.

    Thanks for your fast answer.
    But could you please provide a deeper answer? I would like to know where do you think the problem is. Shouldn't the reference be accepted by Receiver:add, since it can only be seen as a Handle using its private base, or should the dynamic_cast work?
    Aren't we actually trying to cast to a private base? However, casting to private bases directly uses to be rejected in compile time. Should the *this pointer passed from the DspHandle class to Receiver be considered a pure DspHandle or a IODriver?
    Thanks a lot.

  • SG200-08 Newbie Questions

    I have recently purchased the SG200-08 Smart Switch, but I have a few "newbie questions" about it as I get started using it.
    The on board firmware shows 1.0.1.0. Is that the latest firmware to the switch?
    Do I need to enable IPv6 Auto Configuration and DCHPv6 in my switch settings to be ready for IPv6 as my ISP rolls it out down the road?
    How do I go about changing the switch's username? I was able to easily change the password, but having issues getting the username to change.
    Do I need to do anything about the LLDP-MED settings? What exactly is that?
    How do I confugure the System Time Settings so the switch functions in my time zone (USA Central Time)?
    Thanks a bunch for any assistance!

    Hi Nathan,
    My guess is that NAT is already on - you have one public IP address from your ISP. Your router will use NAT (network address translation) to allow multiple clients (and either dynamically assign them private IPs via dhcp or you set them statically) to connect to the internet using the one public IP. It also sounds like your RV042G is assigning both ipv6 and ipv4 addresses, and theres nothing wrong with that. Unless you have specific information re: ipv6 from your isp, however, I would suggest not worrying about it until you hear from them. Are your macs connected to the router via the SG200 switch? If so, it looks like its passing ipv6 just fine.  UPnP is something completely different - thats with opening ports like you mentioned - its a way that your devices can communicate with the router to automatically enable the proper port forwarding for the device/application.
    Regarding the username, create a new user account. I don't think you can edit the cisco user, but try deleting it after creating and testing a new user account..
    I'm not familiar with the Polycom system, but I would leave the settings as default unless you are using true IP phones (rather than an ATA adapter). From a quick google of the polycom device, I don't think you will gain anything from LLDP/CDP as the handsets use regular cordless phone freqs. With my setup, we use cisco IP desk phones and cordless wifi phones, CDP makes life easy as the cisco access point, wifi phones, cisco switch, and cisco desk phones (connected via ethernet) see each other and know what they're dealing with automatically.
    I don't see the SNTP setting for unicast / broadcast that you're looking at. For the switch to get the time from a sntp server, under administration -> time -> sntp settings, add a server, and then back on time-> system time, enable sntp server as the main clock source. What are you using as your sntp source? Do you have an internal sntp server? You don't need to enable dhcp on the sntp server.
    May I also point you to the two manuals, I think they may be helpful:  RV042G  & SG200
    Hope thats helpful.
    Best,
    David
    Please rate any helpful posts.

  • InDesign or Acrobat (newbie question)

    Hi,
    I tried posting this in the LiveCycle Designer forum, but I think it's a bit too much of a newbie question:
    Once in a blue moon when I'm at work, someone will ask me if I can add text fields to a PDF form so that they can easily type onto it and print it out. I've always done that directly in Acrobat (on the few occasions that it's been requested from me). But I was curious about Adobe LiveCycle since it came with CS3, so I played around with it a couple of days ago. I added the text fields in LiveCycle this time, and it seems to have worked fine. Which is the better program for this kind of task? I'm not 100% clear on the *main* purposes of either program or how they compare. If anyone wanted to give me a clue about it, I'd appreciate it!
    Thanks,
    Phyllis

    > I thought perhaps you could add that capability
    You can (I said I was oversimplifying). However there are contractual
    limits - to oversimplify (!) 500 users per form.
    >Which would be preferable -- receiving form data from LiveCycle or Acrobat?
    It depends what you want to do.
    >
    >I wish I knew what the difference was between these two programs. Is it purely a matter of emphasis on one task or another?
    They come to the same problem in different ways. For a simple task
    they may seem pretty much the same. Some differences:
    * A form made in Acrobat is a PDF with form fields stuck on top; it
    remains a normal PDF in every other way. Forms are almost always made
    by preparing an existing PDF, then adding form fields.
    * A form made in Designer is barely a PDF. It's a wrapper round an XML
    file. You can no longer edit it in Acrobat, ever, even for the most
    simple things. PDF files are imported and converted (sometimes with
    loss of quality or features), or forms are made from scratch.
    * Acrobat form fields are fixed size.
    * Designer form layout can be dynamic.
    Aandi Inston

  • Total Newbie Question ... Sorry :-(

    I know it's a windows thing, and I am now converted to Mac but I gotta know this because it's doing my head in. It's a complete stupid green gilled newbie question.
    When installing new programs on a Mac can you create shortcuts to the programs on the Dock? I did what I THOUGHT it would be, i.e I made an Alias and stuck it in the dock, but on rebooting my Mac later on, in place of the shortcuts where 3 question marks which when clicked on did absolutely nothing???
    Help?
    A.L.I
    Windows XP Pro Desktop, Macbook Pro, 60GB iPod Video   Mac OS X (10.4.5)   OS X

    You aren't installing something from a dmg file are you? The dmg is a disk image – kind of a virtual CD. So when you double click the dmg and then get the little disk/hardrive/custom icon on your desktop that is the same as if you had mounted a CD. You then need to drag the application off of that "CD" into your application folder. Then it is truly installed.
    You can then "eject" the icon your your desktop. This is what happens when you shutdown and without remounting the image your dock shortcut can't find the original.
    Just a thought.

  • Newbie Question. just installed IE7.. how do I set up a local host to preview sites?

    Sorry for the newbie question... but it's been a long time since I have done this
    Thanks!

    Just define your site in DW as always.  For a static site, that's all you need to do.

  • Newbie Question about FM 8 and Acrobat Pro 9

    Hello:
    I have some dcouments that I've written in FM v8.0p277. I print them to PDF so that I can have a copy to include on a CD and I also print some hard copies.
    My newbie question is whether there is a way to create a  PDF for hard copy where I mainitain the colors in photos and figures but that the text that is hyperlinked doesn't appear as blue. I want to keep the links live within the soft copy. Is there something I can change within Frame or with Acrobat?
    TIA,
    Kimberly

    Kimberly,
    How comes the text is blue in the first place? I guess the cross-reference formats use some character format which makes them blue? There are many options:
    Temporarily change the color definition for the color used in the cross-reference format to black.
    Temporarily change the character format to not use that color.
    Temporarily change the cross-reference definition to not used that character format.
    Whichever method you choose, I would create a separate document with the changed format setting and import those format into your book, create the PDF and then import the same format from the official template.
    - Michael

  • Dynamic casting

    hello all (happy new year!),
    i am trying to dynamically cast a class that is only known at runtime from the configuration file that is parsed during startup.
    the code is as follows:
    ArrayList classes = new ArrayList();
    ... (parsing)
    classes = JAFSaxParserInstance.getClasses();
    Iterator it = classes.iterator();
    while (it.hasNext())
      Object next = it.next();
      Class appToLoad = Class.forName(next.toString());
      Method instanceMethod = getInstanceMethod(appToLoad);
      Object frame = instanceMethod.invoke(null,null);
      Component[] components = new Component[MAX];
      components = ((UNKNOWN_CLASS) frame).getContentPane().getComponents();
    }without the ability to discover the class from which i have just called a getInstance() method, i seem unable to retrieve all the components of the JFrame subclass (i get a ClassCastException). for my purposes, all of the UNKNOWN_CLASSes will be subclasses of JFrame, but without explicitly being able to cast it (frame) exactly, i cannot extract the components.
    is there any way to dynamically cast such objects at runtime? by this i mean i cannot use switch statements b/c the classes are unknown prior to runtime.
    thanks!

    point well taken. i've probably designed my application wrong if it's this difficult, but let me try to explain what it is i'm trying to do.
    i had previously created a swing application whose central class (bootstrap initialized by a separate class with a main method) is a subclass of JFrame using the GridBagLayout manager. now, since more related gui applications are to be built, i thought it would be nice to build an application framework into which i could insert each standalone application into a JTabbedPane pane of the framework application.
    the application framework has the same structure as my previous application. a bootstrap main method class initializes the main application frame which builds a contentPane which contains a JTabbedPane. as this application framework frame is initializing, it parses an xml file which contains the data pertaining to each class and my DynamicLoader class attempts to load/initialize and add each class into a separate tab in the main application frame. that's where the problem arises since i don't know the exact class that will be loaded--only the xml file contains that information.
    i've read a few things about implementing interfaces in order to get around the inability to cast types at runtime, but am not too sure of how that might work.
    let me know if seeing some more of the code would help or if there's anything i should clarify.
    thanks!

  • Domain name settings - Newbie question

    Sorry for a newbie question!
    I am already pointing a domain name to web hosting for email account. Now, I need an application server to run ERP software and Oracle, and installing Solaris and Oracle need a domain name.
    If I point my domain name to the server, how do I receive emails from web hosting???
    Install an email server to the application server instead? What can I do if I want the same domain name? Any option?

    Setting up a mailserver and making sure it doesn't suddenly turn into a spambox is not something you do with the use of a few commands. I suggest to dive into the Solaris admin guide on docs.sun.com and read up on e-mail and network services.
    If that is asking too much of your time you'll be better off getting your ISP to handle all this for you.

  • Domain Name settings in Solaris - Newbie question

    Sorry for a newbie question!
    I am already pointing a domain name to web hosting for email account. Now, I need an application server to run ERP software and Oracle, and installing Solaris and Oracle need a domain name.
    If I point my domain name to the server, how do I receive emails from web hosting???
    Install an email server to the application server instead? What can I do if I want the same domain name?

    Your questions are completely off-topic for the forum.
    These SunOS forums are for questions on <i>"how do I install my OS"</i>
    You particular question is in the <i>"how can I install Solaris while using the CD drive"</i> forum.
    So, if you had a question on how to edit the /etc/inet/hosts file to establish a FQDN on the computer, then it might be appropriate for the forum.
    Unfortunately, I don't have a clue on where to redirect you, except perhaps to the Sun Java Enterprise System suite of applications?

  • Newbie Question:  How much computer do I need?

    Newbie Question:
    I would like to use MainStage 3 in a live performance environment to play bars, parties, etc.  I'm not looping, using it to playback recordings, processing outboard equipment or vocal processing.  I want to stop carrying Rolands, Nords, Korgs, etc and get to a controller and a rack with a Mac Mini in it.
    I tested a download of Mainstage 3 on my home Mac Mini (late 2012, 3.5 Ghz i5, 4GB RAM, 500GB drive) and it seemed to run fairly well.  $30 well invested so I trekked forward... I purchased a Mac Mini (late 2009,  2.52GHz Core 2 Duo, 6GB RAM, 128GB SSD) for $200.  I started to do more elaborate keyboard setups to see how the CPU would hold up.  It typically runs from 30% to 50% of capacity (CPU and Memory)  It actually boots and runs better than the i5.  I hear the occasion gitch, but it actually seems to be getting better in time (or I'm rock and roll deaf.
    I got a rack, an Airport Express, a Radial USB interface and a Nektar Panorama P6.  It's starting to get expensive, but I'm emboldened by the actual quality for the sound and the flexibility of arranging for live performance.  What used to take me two and three keyboards to play, I can now fit on one performance patch.
    OK, now the question... am I at the limits of this little Core 2 Duo?  Should I upgrade the i5 with more RAM and a bigger SSD and use that?  Should I get a new(er) i7 and bite the $1,500 bullet for the additional RAM and SSD?
    I see that most of you are running pretty nice Macbook Pros with i7 and lots of everything.  My needs are modest; am I OK? 
    BTW, I want to run a Mac Mini in a box because I don't want to carry a laptop out in the open.  If I was doing bigger shows I wouldn't care but I play some rowdy bars and constantly have folks hanging off me while I'm playing.  It's fun, but hard on gear.  If you can't drop it or dip it in beer, it won't last long where I work.
    Matt Donnelly

    Rule of thumb: newer and faster is better. But, depending the complexity of your needs you may be OK with an older Mac. Some glitches that happen in a live performance are due to loss of communication with USB or Firewire inputs, so make sure they're secure. I recently upgraded from a 2010 Mac Mini 2.6 dual core with 16 GB RAM, which was used live for nearly four years, to the latest Mac Mini 3.0 i7 with 16 GB RAM and a 500 GB SSD. I was getting an occasional stuck note with the older one. The new one is rock solid. Some of my patches may have up to a dozen channel strips mapped to three keyboards. The Mini is mounted in a rack next to a MOTU Ultralite Hybrid. It is a good idea to map a panic button on your keyboard to controller # 123(all notes off). Also, you might want to invest in a battery backup power supply(APC, Cyberpower, etc.-$40-$60) to protect your Mac against power loss, which can damage you hard drive.

  • Newbie question - XML version, searching by artist

    Probably quite a common problems - apologies for newbie questions.
    I've changed the URL of my MP3s in my XML to a new location and refreshed my feed. Is there a way of seeing what version of the XML iTunes is using? (it takes around 24 housr to refresh, right?)
    Also, when I'm searching for my podcast by author it's not coming up (<channel><itunes:author>) - is there a reason for this or a way to get it to show up when people search for the artist, other than doubling it in the title? (This works by the way, but I'd prefer not to!)
    Thanks.

    you can do it in just one loop, going through all the image
    tags in index_content and for each tag fill the values of all four
    arrays
    for (i...) {
    get the appropriate child of index_content
    first_array[ i ] = value of first tag
    second_array[ i ] = value of second tag
    no need for multiple loops.
    flash has functionality for xml files, but it helps to write
    a little wrapper around it, to simplify programming, especially if
    you work with xml a lot.. I wrote my for work, so I can't show it
    to you, but it's not very complicated to do

  • Add Question dynamically in crm survey

    How to add the question dynamically in crm survey?
    I checked the two class CL_CRM_SVY_BUILDER and  CL_CRM_SVY_DOM.
    IN htis method Insert_question method is there.
    But how to use this method. What value should we pass in node.?
    If anybody knows about it, then please let me know.

    HI Dezpo,
    Thanks a lot for replying.
    I had checked the updated <b>SAP Note 834573</b> -Interactive Forms based on Adobe software: Acrobat/Reader version, which states that:
    For SAP Interactive Forms by Adobe, you require the following:
    Adobe Acrobat as of Version 7.0.9
    Adobe Reader as of Version 7.0.9
    <b>Important:</b>
    Note that you can only have limited use of Reader 8.0 for forms that, at runtime, are integrated in a WebDynpro application through the xACF technology (Active Components Framework). In this runtime environment, Reader 8.0 currently only supports static interactive forms. If you are using <b>dynamic interactive PDF forms</b>, we recommend that you use <b>Reader 7.0.9.</b> In the application, you can use parameters, or you can call methods, to determine whether you want to create a static or dynamic PDF form.
    I tried with the reader versions - 7.0.7,  7.0.9 and 8.01, but it doesn't work for either of them.
    Regards,
    Siddhartha Jain

Maybe you are looking for

  • Smartform issue with page break

    Hi All,          I have an unusual issue with page break. Here is my scenario, I have a group of items in my table main area and for each group there is sort of header that prints. Similarly there are multiple groups needing a header whenever there i

  • FormCalc. Hiding the subtotal footer in PDF form

    Hi, LCD gurus! I've got a problem that I'm unable to solve for a couple of days. There is a PDF form (consignment note) with header, lots of positions and footer. The original task with it was to make the last position of the data table be on the sam

  • Maximum Number of Apple TVs in One Home

    How many Apple TVs can be installed in one home with one iTunes account?

  • I can't click on some items on the upper part of every page I go to.

    I have been trying to click on some items on several pages and I realized that the upper part of the page is not even responding to my left and right click. I was lucky enough to be able interact on this part of the page. For example, I can't left cl

  • Down payment  in AR

    Hi I am little confused about down payment requst and clearing process.I understand that it does not follow the double entry system.Can some one take the pain to explain me how to clear the down payment process ? Thanks in advance Satya