Dynamic casting in java

Hello everyone....
i am having a problem as follows:
i have a method in my project which is taking a reference of object type...
i want to cast the object to the passing type,bt i dont want to cast explictily inside the method...
can something be done by which the object itself get casted to passing type automatically by determining the runtime of the instance being passesd at runtime?
public void change(Object o)
/// i want to cast this object to A type without explicit casting.... can it be done through reflection or some other method?
call of the above method from main///
p.s.v.main(String[] args)
A a =new A();
a.call(new A());
}

807784 wrote:
can something be done by which the object itself get casted to passing type automatically by determining the runtime of the instance being passesd at runtime?When you cast an Object to a specific class or interface you are telling the compiler that the object is really of that class or interface. The only thing a cast does at run time is to verify that the actual object is of the specified class. Hence, for a cast to do any good, it must be present at compile time.
I don't know exactly what you are trying to do, but you might want to look at the visitor pattern.

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

  • How can i create an dynamic report in Java

    hello everybody,
    I want to make dynamic reports in Java. Report contain data and images with good layout.. such as crystal reports presentation..
    Reports fields decided at run time or we can say that it is generated according to user requirement...
    can it is possible in Java. If it is then which tool is better for it..
    please suggest me.. this is very urgent requirement for me...

    i don't know what types of tools are avaiable in market... Tools for what? You still didn't tell us what exactly you want to do.
    i just imagin that
    "An user create a database dynamically on server
    databaseNobody "dynamically creates a database".
    and he decide reports desgin according to
    his requirement..... we provide an control for this
    type possibilities....."
    so this is question is build in my mind.. so i
    forward this question to this forums..
    I am just going to check the physibility of my mind
    imagination...Feasibility you mean. IMHO, the feasibility of creating that stuff yourself is very low. Reinventing the wheel usually doesn't make it better, and it's likely to be more expensive to pay you for creating an inferior solution (not because of lack of skills, but simply because the available products had a few years time to grow, feature-wise) than to simply buy the licenses. Look at Crystal Reports or JFreeChart or Jasper Reports. Or use Google to look up J2EE-based reporting libraries. There might be more.
    Which of these is best, I don't know, I never used any of those. Also, the definition of "best" changes with the requirements. What's better, a Ferrari or a truck?

  • Getting Error:::oracle.jbo.domain.Date cannot be cast to java.lang.String

    Hi Friends,
    I have simple req'.
    i have one date filed in OAF page...if user has change the date filed..means if he incresed by 2 days..then i need to call one procedure..if not no need to call....
    first am picking that date field to by uusing prepared stmt and putting in to one variable..like below
    try {
    ps1 = am.getOADBTransaction().getJdbcConnection().prepareStatement("SELECT -------");
    ResultSet rs2 = ps1.executeQuery();
    while (rs2.next()) {
    schDate = rs2.getString(1);//storing the value
    } catch (Exception e) {
    throw OAException.wrapperException(e);
    Next..am picking the current value like this(user can change the value) like below...
    OAViewObject viewObj = (OAViewObject)am.findViewObject("simpleVO");
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");
    java.text.SimpleDateFormat dtFormat = new java.text.SimpleDateFormat ("MM/dd/yyyy");
    StringBuilder date = new StringBuilder(dtFormat.format(currSchDate));
    Then am comparing the values like below..
    if (schDate.equals(date)) {
    String outParamValue = "";
    String secondOutParamValue = "";
    but am geting the below error
    ## Detail 0 ##
    java.lang.ClassCastException: oracle.jbo.domain.Date cannot be cast to java.lang.String
         at xxuss.oracle.apps.abc.webui.xxPGCO15.processFormRequest(xxGCO15.java:594)
    Appriciate any help...its very urgent
    Regards
    Harry

    Instead of :
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");Try
    String currSchDate = viewObj.getCurrentRow().getAttribute("iDate").toString();
    -Anand

  • Java 7 update 51 cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints

    Since I installed Java 7 update 51 accessing the EMC VNX Unisphere Console cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints.
    I rolled back to Apple Java 1.6 -005 now I am getting the following error: plug-in failure.
    I think this is cused by the fact that the EMC console application has been written for java 7 and not java 6. Has anybody faced and solved the "java.util.HashMap cannot be cast to java.awt.RenderingHints." error ?

    Hi Yaakov,
    The error is thrown from the  eclipselink.jar:2.5.1 which is a JPA provider .
    Is the above jar bundled in the Oracle Product you are working upon or was this downloaded from external site ?
    If the jar is bundled with the Oracle Product, go ahead a log a SR with Oracle Support with Toplink product group to drill down on the issue, as the issue is happening internally or thrown by the Eclipselink implementation and we've no control....
    Hope it helps!!
    Thanks,
    Vijaya

  • 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!

  • Get / Cast a Java Object

    Does anybody know how to get (or Cast) a Java Object returned from a Java method call ?
    Example:
    <cfset someList = object1.method1(someString, JavaCast("float",someNumber),...)>
    This method returns a list of Java object of type "Object2". ie. it returns List<Object2>
    Now I attempted to loop thru each objects from the returned list, and invoke some method on them, using code similar to below,
    <cfset var="#someList[index]#"/>
    but ColdFusion does not seem to understand the object "var" as Java "Object2". Is there any way I can cast the "var" to "Object2"?
    Thanks in advance.
    Xiaoling

    "var" is a reserved keyword! You can initialize variables with "var" in the beginning of a component, but do not use it as a variables name:
    <cfset var someVar = "#someList[index]#">

  • How to create dynamic images in java servlets?

    I want to create dynamic images in java servlet. Can servlet create dynamic images that based on the input data files? The results can be displayed in GIF, JPG..format? how can this be done? any example in internet?
    What OS do I need to install and what other requirements needed if i want to build up a servlet server?
    Thanks a lot!

    Also worth having a look at SVG http://www.w3.org/TR/2001/REC-SVG-20010904/, you can get a viewer at http://www.adobe.com/svg/ or you can use Batik http://xml.apache.org/batik/index.html to convert SVG to other formats such as JPEG.
    HH

  • Dynamic loading in Java

    I was asked following in the interview-
    What things are dynamically loaded in Java?
    How can we change this behaviour so as to load things statically?
    Can anybody clarify this for me or give some reference URLs etc?
    Thanks in advance.

    I was asked following in the interview-
    What things are dynamically loaded in Java?
    How can we change this behaviour so as to load things
    statically?
    Can anybody clarify this for me or give some reference
    URLs etc?
    Sounds like an absurdly general question to me.
    For example shared libraries are loaded dynamically. And there is no way to do it statically unless one modifies the jvm.
    Or using Class.forName() loads a class dynamically. Statically one could create a null reference which would be a 'static' load. Of course that is a rather tentative definition because java is still going to load it when the method is reached rather than on start up.
    Or one could say that the core jvm is statically loaded, for example the system class loader, since it is implemented in C (but of course it actually exists in a shared library so it is loaded dynamically as well by the OS.) All other classes are loaded dynamically and again it requires changing the JVM to alter the behavior.

  • 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.

  • Weblogic 10.3 error apache ListOrderedMap cannot be cast to java HashMap.

    Hi All,
    I'm having following code which is using spring(version: 2.0) dao
    public Map<String, String> getEmplyeeMap() throws Exception {     
              StringBuffer query = new StringBuffer("");
              query.append("select emp_name,dept_name from EMPLOYEE order by emp_no");
              logger.info("Inside getEmplyeeMap...Query to be executed :"+query.toString());     
              Map<String, String> EmpMap = new LinkedHashMap<String, String>();
              List<Map<String,String>> l_lstQueryRes = (ArrayList<Map<String,String>>)getJdbcTemplate().queryForList(query.toString());
              logger.info("l_lstQueryRes:"+l_lstQueryRes);
              if (l_lstQueryRes != null)
                   for (int l_iLoop = 0; l_iLoop < l_lstQueryRes.size(); l_iLoop++)
                        Map<String,String> l_mapRowData = new HashMap<String,String>();
                        l_mapRowData = (HashMap<String,String>)l_lstQueryRes.get(l_iLoop);                    
                        EmpMap.put(l_mapRowData.get("emp_name"), l_mapRowData.get("dept_name"));
                   }//End of for loop
              }//End of if loop          
              logger.info("EmpMap list size is.." + EmpMap.size());
              return EmpMap;
         } //End of getEmplyeeMap
    getting below error
    org.apache.commons.collections.map.ListOrderedMap cannot be cast to java.util.HashMap
    I'm thinking this problem is occurring because of jdk1.6 version, is anyone come across this problem?? This same working good in weblogic9.2 version.
    Thanks advance.
    Regards,
    Sharath.

    user9222505 wrote:
    Ok, thanks. So how do i determine where we are at since I have this "465"? How does that relate to a particular patch?
    Logger@9214443 3.5.3/465I believe, you are on 3.5.3 unpatched, and if I correctly remember, after applying the 3.5.3 patch 4 it should like like 3.5.3p4/... or 3.5.3.4/... (don't remember which one)... You would have to download that patch from your Oracle Support website (whichever you use), and apply the patch to a pristine extracted directory of 3.5.3 according to instructions in the patch zip.
    Starting with a recent version no more manual patching is necessary and you can download full distributions of patched versions from Oracle Support, but I don't think that applies to 3.5.3, yet (although it is possible that they recreated patch artifacts like that for earlir versions).
    If you do not have a support contract then you cannot download a patch or patched versions. You can only download a new full release which always has any previously released patches incorporated, though 3.5.3 is the last 3.5 full release if I correctly remember... and 3.6 comes with code incompatibilities at a few places so it is not a drop-in replacement...
    Best regards,
    Robert

  • How to resolve oracle.jbo.Key cannot be cast to java.util.List?

    Hi experts,
    I am getting this error (oracle.jbo.Key cannot be cast to java.util.List) PPR# . . . . . while filtering in grid..
    give some idea to solve this please...
    Note: (This error is occurs only in JDev ver 11.1.1.3.0 and its working fine in 11.1.1.2.0)
    Regards,
    Gops

    I guess information is too less, could you provide some more info ?
    Amit

  • Why objects are  dynamically created in java

    Why objects are dynamically created in java even if dynamically created object requires more space & more memory references as compared to static object?

    I don't even know where to start...
    KAMAL.MUKI wrote:
    Why objects are dynamically created in javaWhat is the alternative?
    even if dynamically created object requires more space & more memory referencesCan you prove that?
    as compared to static object?Can you define "static object"?
    I vote "troll".

  • Linklist and dynamic array in java?

    how to define linklist object and to build dynamic array in java?

    with so little information, all one can do is pointing you to :
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html

  • Can I do dynamic class cast with java SE1.4.2?

    Hi,
    I have some question on dynamic class cast.
    I'm using java SE1.4.2. Suppose I have a method :
    castObjectToSomething(Object o)
    Something s = (Something) o;
    However, I don't know what is the class to cast until runtime. How can I do a runtime class cast?
    I know that java 5.0 have a Class.cast() method which java1.4.2 does not have. But can I do the same stuff by using SE1.4.2?
    Thank You!!!!!
    oh_silly

    There is no sense in wanting to cast to a class that is only known at runtime. Because you can't do anything with such a class during runtime. Even though you could technically retrieve the class name, the method names and the parameter names, you could do nothing with this class as you don't know what it is doing. If you would know what it can do, you would know it also during compile time and then you would know the classname/interface name you want to cast to and can import it and use it reasonably.
    Tell us the requirement that you think you have and we will proof you that you don't need such a requirement.

Maybe you are looking for

  • Can I convert from pdf output into excellsheet in smartforms

    My smartform output is in pdf form now .Can i convert it into excellsheet by using save option. Moderator message: please do some own research before asking. Edited by: Thomas Zloch on Feb 21, 2011 12:49 PM

  • Signature problem again

    I finally learned to set the program right and could get random selection BUT once I set it up it works once and then refuses to remember what it was supposed to be doing. When I go to the first column on the Signatures page I find a picture of a pen

  • VBRP Z fields update by bapi ?

    Hi, i have to update some Z fields in table VBRP. Which bapi can i use to maintain these custom fields ? with kind regards, Hans

  • Budget Exhausted Error

    Hi Experts, I am facing a problem in Production server, related to the Budget Exahusted , I had created a PR & PO last months and now today when i am goint to make a change in Delivery date. Sysetm is giving Error of Budget Exhausted... were as we ha

  • No accessories with iphone 5.

    I ordered an iphone 5 from the apple store and have only just realised that it didn't come in the normal nox ie with headphones, charger etc. I haven't opened the packaging and have receipts. Can I go into an apple store with everything and claim it?