Casting the Object dynamically

Hi All,
I am looking for a way to dynamically cast the object. I am receiving an object which is JAXB object as parameter of a method. This object can be type pf one the 5 jaxb objects my logic is handling. I need to identify the actual type of object and perform some operations on it.
Each of these 5 JAXB objects have some common method (although these objects does not inherit from any common class) and some methods which are specific to them.
I can not make changes to JAXB classes as i am importing those as jar.
I know it will need reflection somehow but i am not sure how to do it exactly. Below code will give you idea what i am trying to achieve. Its giving compile time error as xngEvent is typecasted in if-else block. This is just to show what i want to achieve using reflection.
public void processMessage(Object inputObject)
if(inputObject instanceof com.att.granite.jaxb.xngevents.dtd.equipment.XngEvent){
                    com.att.granite.jaxb.xngevents.dtd.equipment.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.equipment.XngEvent)inputObject;
               }else if(inputObject instanceof com.att.granite.jaxb.xngevents.dtd.cable.XngEvent){
                    com.att.granite.jaxb.xngevents.dtd.cable.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.cable.XngEvent)inputObject;
               }else if(inputObject instanceof com.att.granite.jaxb.xngevents.dtd.ipaddress.XngEvent){
                    com.att.granite.jaxb.xngevents.dtd.ipaddress.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.ipaddress.XngEvent)inputObject;
               }else if(inputObject instanceof com.att.granite.jaxb.xngevents.dtd.ipsubrange.XngEvent){
                    com.att.granite.jaxb.xngevents.dtd.ipsubrange.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.ipsubrange.XngEvent)inputObject;
               }else if(inputObject instanceof com.att.granite.jaxb.xngevents.dtd.path.XngEvent){
                    com.att.granite.jaxb.xngevents.dtd.path.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.path.XngEvent)inputObject;
               }else{
                    com.att.granite.jaxb.xngevents.dtd.site.XngEvent xngEvent = (com.att.granite.jaxb.xngevents.dtd.site.XngEvent)inputObject;
String database = xngEvent.getDatabase();
String elementType = xngEvent.getElementType();
String editOperation = xngEvent.getEditOperation();
validateEvent(elementType,editOperation,xngEvent);Thanks,
Aashu

What you are talking about is called runtime class working. It can do the job you want but for reasons the other responders already mentioned I cannot recommend it for your use case. The primary reasons being the complexity involved, the likelihood that you will need changes that will not be backward compatible, the difficulty in testing and debugging and the difficulty in finding developers that will even understand this approach that can take over after you are gone.
This type of functionality is very roughly related to the use of dynamic proxies and code injection used by Spring and other frameworks.
With those caveats in mind this is a link with an excellent example of how to do it and the issues involved.
http://www.ibm.com/developerworks/java/library/j-dyn0610/
For your use case I would recommend the approach you have probably already settled on. But first follow gimbal2's advice and document your requirements and use case and the dependencies on possibly duplicated code sections you previously mentioned.

Similar Messages

  • EJB3 Stateful:ClassCastException when casting the object returned in lookup

    Hi,
    I'm developing a web application that make use of EJB3 stateless and stateful beans. The application server is the Websphere Application Server 6.1.0.15 with the EJB3 Feature Pack installed and the web server is the IBM HTTP Server running in another machine.
    The problem I'm facing is that for every stateful bean after the lookup, it throws a ClassCastExcption when casting the object returned. See part of the log below.
    [7/13/08 3:15:48:869 CDT] 0000001c SystemErr R java.lang.ClassCastException: cannot cast class com.spcs.dsa.ejb.authenticationmanager._AuthenticationManager_Stub to class com.spcs.dsa.ejb.authenticationmanager._AuthenticationManager_Stub
    at com.ibm.rmi.javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:396)
    at com.spcs.dsa.ejb.client.DsaEjbClient.getAuthenticationRemote(DsaEjbClient.java:37)
    at com.spcs.dsa.action.NewCardAction.execute(NewCardAction.java:85)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    Please notice in the log above that the cast was done for the correct class.
    Here is the java code:
    AuthenticationManager auth =
    (AuthenticationManager) javax.rmi.PortableRemoteObject.narrow(
    context.lookup("com.spcs.dsa.ejb.authenticationmanager.AuthenticationManager"),
    AuthenticationManagerStub.class);
    This problem doesn't happen for statless beans. If you simply change the class to be stateless, this problem stop to happen.
    If you run this code in a stand alone program, this problem doesn't happen. It only happen when running in the web server.
    Does anybody know what should be done to solve this problem ??
    Thanks,
    Marcos.

    I'm not familiar with any specifics of IBM's implementation but from an EJB 3 spec perspective there is no need to use PortableRemoteObject.narrow() if you're retrieving an EJB 3.0 Remote Business interface, regardless of the component type( stateful vs. stateless). In addition, the "_Stub" class should never have to be part of your client programming model. That should be hidden within the vendor's implementation, if present at all.
    If AuthenticationManager is the Remote 3.0 Business Interface
    @Remote
    public interface AuthenticationManager {
    your client lookup should be :
    AuthenticationManager am = (AuthenticationManager) context.lookup("...");

  • Re-casting of object from control reference

    I feel like this question is likely answered elsewhere, but after days of searching I couldn't find an answer. Sorry if I'm missing the answer in some obvious place.
    I'm given a reference to a cluster control and told that the elements of the cluster are all children of parent class A. Using the controls[] property I get an array of the elements, and the value property of each of those elements gives a variant that can be turned into class A. At that point, all of the object oriented overriding and private data stuff works as expected.
    So far so good.
    But one method I call on those objects changes the private data, and I need to update the control with the updated object. There I get a runtime error because the control isn't A but some child class of A.
    I think this is where Preserve Runtime Class comes into play, but since I only get a reference to work with, what do I do? This is especially frustrating because debugging probes show that LabVIEW knows the child class on the wire, but I can't see how to tell LabVIEW to cast down to the class that it knows it has.
    For example, is there some way to use the ClassName property of the control to cast the object of class A into the child that the control is expecting?
    Solved!
    Go to Solution.

    nathand wrote:
    So your trying to write to the specific control within the cluster, by reference, as a variant, and you're getting an error? What's the actual text of the error?
    Really you shouldn't ever be using a front panel object this way, especially one where the user never sees the data in it. For passing data around you should use a wire. Neither a wire nor a DVR will get you the ability to pass an arbitrary cluster, though, which it sounds like is what you're trying to do. With a bit more information we might be able to suggest a better approach.
    I don't have the text of the error handy, but it comes from the write value property node and basically says the given variant can't be converted to the type of the control. It happens only when the value is cast to the parent class, which makes sense.
    In other words, given a control of child type,
    control.value ---> variant ---> to parent ---> variant ---> control.value     failes with the error
    control.value ---> variant ---> to child ---> variant ---> control.value       succeeds
    So a solution would be a way to cast to the child instead of to the parent. LabVIEW knows what class the control contains; it is listed in a number of places from the ClassName property through the probe window. The problem is I know of no way to bridge the gap from "LabVIEW knows what class this thing is" to "have LabVIEW cast the variant to that class."
    I completely agree that I shouldn't have to ever be using a front panel control this way, but I don't want to get sidetracked into talking about the shortcomings of LabVIEW that have required such a use. Suffice it to say, that is the assignment.

  • ClassCastException on casting same objects differing in canonical name

    Hi all,
    I have got a problem with class casting. Some years ago I comitted the error not to bundle my classes in packages and now I need to do so. Unfortunately I can't deserialize previously saved objects from files anymore using ObjectInputstream, I get a ClassNotFoundException.
    file = new File(filename);
    FileInputStream fos = new FileInputStream(filename);
    ObjectInputStream oos = new ObjectInputStream(fos);
    try
         _transaktionen = (ArrayList) oos.readObject();
    catch (ClassNotFoundException e)
         JOptionPane.showMessageDialog(null, "Loading error (transaction)" +
                                            "\n"+e.getMessage());
    } Finding out their serialVersionID and make it explicit does not help either, so I created a copy of the class to deserialize in a package, since I need to reference to the class, and left anotherone in the default package.
    My problem now is that I can deserialize the objects, but cannot cast the object from the file to the type of the class in the package.
    //getting transactions from the arraylist previoulsy loaded from the file with iterator "it"
    DBFensterSeite aktuelleSeite =
                        new DBFensterSeite((Transaktion) it.next(), 1, null);Both have been loaded by the same ClassLoader, have the same serialVersionID and only differ in the canonical name (one is called Transaction, the new one is called packagename.Transaction). I am not quite sure whether this is the error, maybe you can help me. Thanks in advance!
    Regards,
    S�ren

    >
    Yes, technically you can. It does however require
    that you compile the new classes using a pre 1.3
    compiler. Then you just use them with the newer
    compiler.You mean, in Java 1.3 it was possible to reference classes in the default package?
    >
    You should look into providing a migration process
    however. Before installing the new application run
    another application that 'reads' the old stuff and
    'writes' it to a new location. That way your new
    application doesn't need to deal with the old stuff
    at all.Well, yes and no. The program implicitly executes a conversion on reading the file. Once you save it, it's in the new format (and thus unreadable for the old program). I do not want to provide a static conversion at installation time, because the customer, hopefully, backups data in the old format. He would not be able to read it after restoring data or, if there was something like a conversion function or program, would find it annoying having to think about it. In the end, they asked me to write the program for keeping it as simple as possible :-)
    I'm quite happy about the way it works now; the new cast-methods enable me to change the data types interfaces without having to bother about anything. ;-)
    Who gets the dukes now? :-p

  • Cast Reflection Object

    Hi,
    I'm in the following situation.
    I've a XML file where Java-Class names are defined.
    I parse the file and create new instances of the classes,
    but I need to cast the Reflection Object to the read-in class,
    how can I do this.
            String className = "misc.Test";
            try {
                Class<?> c = Class.forName(className);
                Object o = c.newInstance();
                ((className)o).sayHello();  // <-- That's what I need.
            } catch (Exception e) {
                e.printStackTrace();
    ...Hope s.o. can help
    thx.

    Thank's for you answer.
    Using an Interface or an abstract class, that's the way I would do it myself, but unfortunately, I don't have access to the classes source code, so I can't make them implement an Interface.
    Let's make an example, assume the following mapping in the xml file:
    Abstract Type(non Java)          Java Classes
    Button                      -->           TextButton
    Button1                     -->           ImageButton
    -------------------------------------------------------------------Because of the mapping I know what class to use at runtime, but these
    classes all provide different methods.
    So is there realy no chance to cast the object ?
    regards ...

  • Getting references to the objects in a VM to dynamically link MBeans

    Hi, I am dynamically generating MBeans and using Apache BCEL to change the resource classes to link themselves to the MBeans. The objective is to instrument applications wich we can't access the code and, if possible, do it on a running one.
    I could use the Instrumentation API to change the classes of the application and the Attach API to do it on a running application, but only new instances would be affected, so the previously created objects would not be managed. I can generate MBeans in many ways, but can't link them to already running application objects.
    So, what i want to know is in the title: is there a way to get references to the objects actually loaded in a Virtual Machine or another way to link an MBean to a running object?
    I saw McManus talk at Sun One 2006 about the different ways to link MBeans to application objects, but all of them look to need code changes or previous suport to dependency injection, for example.
    http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-3523.html
    I need it to a technical writing, so an official word can be enough, or even more helpful than a solution.
    Thanks,
    Gustavo

    Gustavo,
    Assuming I understand your question correctly, the only way I can see that you can enumerate instances of objects in a Java VM without changing the classes of those objects in any way is to use JVMTI <http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html#Heap_1_0>. That requires you to write native code somewhere as part of your solution. It is applicable to already-running apps via attach-on-demand <http://java.sun.com/javase/6/docs/jdk/api/attach/spec/index.html>. The MLet service from the JMX API might be convenient here to bridge from the jar file that the Attach API expects to the native code that you need to access JVMTI.
    As you can see this is pretty advanced stuff, but your ideas are interesting and I'd be interested in knowing how they work out.
    Regards,
    �amonn McManus -- JMX Spec Lead -- http://weblogs.java.net/blog/emcmanus

  • PS CC 3D - can you cast a shadow but not render the object?

    Hey guys,
    In PS CC, is it possible to render a 3D shadow + reflection, but have the object that is casting it invisible?
    So the end result is a shadow/reflection on it's own separate layer?
    Cheers,

    Here's one way that might work:
    Make your 3d object including shadows on one layer, then in the Properties panel for the object mesh check Invisible.
    Duplicate the layer and in the Properties panel under Scene uncheck Shadows
    That should give you one layer with only the object visible and one layer with only the shadow visible.

  • Example of generating excel dynamically in ssis? geting error [Excel Destination [190]] Error: Opening a rowset for "Excel_Destination$" failed. Check that the object exists in the database.

    example of generating excel dynamically in ssis? geting error [Excel Destination [190]] Error: Opening a rowset for "Excel_Destination$" failed. Check that the object exists in the database.

    Hi Vijay
    Can you be little bit more specific, did you receive this error when you are designing this pacakge using BIDS
    Becuase when you are designing this pacakge in BIDS, you need to manaually create a excel sheet manually for the first time you run,
    are you creating excel sheet using execute sql task and excel connection with input from a variable?
    Did you receive this error in validation phase or execution phase ?
    Can you share your query to create table in excel ?
    http://sqljunkieshare.com/2012/02/28/how-to-create-and-map-excel-destination-dynamically-in-ssis/
    Use the above post

  • Casting of object reference

    Hi all,
    i have two classes 'super' and 'sub'. 'sub' inherits from 'super'.
    I have got a reference of type 'super' which points to an object of type 'sub'.
    How can i cast the reference from 'super' to 'sub' without knowing the class 'sub'???
    With RTTI i just got the name of class 'sub'....
    thx in advance.
    Regards,
    Markus

    Hello Markus,
    I think you cannot cast the second object reference, since you cannot define an object reference of the actual type of the subclass as target (because the type is not visible statically when it is defined in another program).
    However, you can dynamically create an object of such a class by using its absolute type name:
    CREATE OBJECT go_sub TYPE ('\FUNCTION-POOL=THE_FUNCTION_POOL\CLASS=THE_LOCAL_CLASS').
    Afterwards, you can invoke methods dynamically:
    CALL METHOD go_sub->('THE_METHOD').
    Of course, the syntax checker cannot verify these method calls during design time. To ensure that a specified method is callable for a given object during runtime, you can use RTTI before doing the call.
    As already discussed in this forum, it is not good practice to use local classes from other programs. They can have dependencies to their context (e.g. a global variable of the program where they are defined).
    Hope this helps,
    David

  • Can not cast from object to int

    Hi All,
    I have the following bunch of code
    Session session;
              session = getSessionFactory().openSession();
              Query query;
              int MaxPageId = 0;
              List list;
              try{
                   query = session.createQuery("select max(emp.id) from EmpBean emp");
                   list = query.list();
                   MaxPageId = (int) list.get(0);
                   return MaxPageId;
              catch(Exception e){
                   System.out.println(e.getMessage());
              return MaxPageId;
    The query executed successfully but when i get the max id in a integer variable by the following statement
    MaxPageId = (int) list.get(0);
    I get the following error "can not cast from object to int"
    Please suggest for the same.
    -Thanks

    Cast to an Integer, not an int, and let autoboxing turn the Integer into an int.
    int maxPageId;
    maxPageId = (Integer) list.get(0);You can't cast objects into primitives.
    Autoboxing isn't casting.
    And use Java naming conventions. Local variables start with a lower-case letter.

  • Creating and Binding View Objects dynamically : Oracle Jdeveloper 11g

    Hello,
    We are trying to create and bind view objects dynamically to adf data visualization components.
    The view object is a result of multiple tables.
    We are using Oracle JDeveloper 11g Technical Preview. ( can't upgrade to TP2 or TP3 now).
    We have found this : http://radio.weblogs.com/0118231/stories/2003/07/15/creatingUpdateableMultientityViewObjectDefinitionsDynamically.html on our search for the same.
    The sample application however, is in 10g , hence required migration.
    Also, it was a standalone application with the TestClient.java having a main() method.
    Our requirement is for Web Application; we use Adf+jsf .
    Guidance of any sort is very much appreciated.
    Thanks in advance.
    -Anil Golla

    Hi,
    there also exist a forum for JDeveloper 11: JDeveloper and OC4J 11g Technology Preview
    What you are trying todo is not trivial because you need to not only dynamically create the VO, you would also dynamically need to create the binding meta data for it (assuming you use ADF). Not sure if the API to modify the binding is public, so posting it on the JDeveloper 11 forum bears a glimpse of hope for an answer
    In JDeveloper 10.1.3 you can't do this
    Frank

  • How to create objects dynamically (with dynamic # of parameters)

    I need to create a set of objects based on a definition from an XML file (obtained from the server) and add them to my scene.
    I understand how to create the object using getDefinitionByName (and the limitations regarding classes needing to be referenced to be loaded into the SWF).
    But some objects require parameters for the constructor, and some don't. The XML can easily pass in the required parameter information, but I can't figure out how to create a new object with a dynamic set of arguments (something akin to using the Function.call(obj, argsArray) method.
    For example, I need something like this to work:
    var mc=new (getDefinitionByName(str) as Class).call(thisNewThing, argsArray)
    Currently this is as far as I can get:
    var mc=new (getDefinitionByName(str) as Class)(static, list, of, arguments)
    Thoughts?

    I think what Dave is asking is a bit different.
    He's wanting to know how to invoke the constructor of an object dynamically (when he only knows the # of constructor arguments at runtime).
    This class I know will do it but seems to be a hack:
    http://code.google.com/p/jsinterface/source/browse/trunk/source/core/aw/utils/ClassUtils.a s?spec=svn12&r=12
    See the 'call' method, which first counts the # of arguments then invokes one of 'n' construction methods based on the number of constructor args.
    I've yet to find a clean AS3 way of doing things ala 'call' though.
    -Corey

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • How to cast an Object into a specific type (Integer/String) at runtime

    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    Example:
    public class TestCode {
         public static Object func1()
    Integer i = new Integer(10); //or String str = new String("abc");
    Object temp= i; //or Object temp= str;
    return temp;
         public static void func2(Integer param1)
              //Performing some stuff
         public static void main(String args[])
         Object obj = func1();
    //cast obj into Integer at run time
         func2(Integer);
    Description:
    In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
    For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.

    GDS123 wrote:
    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
    Look into
    Class.ForName(String)

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

Maybe you are looking for

  • Client-cert auth impl in web.xml does not work in Oracle Application Server

    Hi, I am new to implementing security features on the web applications.. I have developed a new web service using jdev1012 and deployed in OAS 10.1.2. Its working fine according to the business requirements, but I am in need of implementing client-ce

  • Creating Time Dimension from date columns in fact tables.

    I remember watching a demo from a BI Tool a couple years ago, wich I swear was OBIEE, and the presentator stated it was possible to create a Time Dimension in the admin tool, based on a date column in other table. Can you guys tell me if there's such

  • Stop price update of  delivered but un-invoiced (non-invoiced) line items

    Hi Gurus, I need some help regarding price update of line items which are delivered but not invoiced yet. Case 1: I am calling the FM 'BAPI_SALESORDER_CHANGE' and passing the line item (say 10) whose price needs to be updated. This line item is neith

  • Strange image problem

    Hello all, I encountered an odd problem today. I have a simple artist website. Today I reorganized it and created an additional basic page for links using an existing page of mine as a template. For some reason, my background image would not show on

  • How to display data depend upon ListBox value?

    Hi Experts and Particularly Hema, As I asked before how to display data in the ListBox, I got an very good response from you all(particularly Hema) . Now what my doubt is asked with sample scenario below: In Screen Painter - Two fields namely : One L