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

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("...");

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

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

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

  • Production Order Error: "Unable to cast COM object of type 'System.__ComObj

    Hi all,
    I have the following code:
    Dim oProdOrders As SAPbobsCOM.Documents
    oProdOrders = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oProductionOrders)
    after the second line I get a system exception: {"Unable to cast COM object of type 'System.__ComObject' to interface type 'SAPbobsCOM.Documents'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A6DA575B-E105-4585-9F4B-50CC4044EEDD}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."}     
    If I change document to eg oQuotations it proceeds normally.
    Any Idea?
    Thanks in advance,
    Vangelis

    try it as
    Dim oProdOrders As SAPbobsCOM.ProductionOrders
    oProdOrders = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oProductionOrders)

  • Reflection objects and thread safety

    Hi,
    I believe that I saw that Field and Method objects are thread-safe (i.e., can safely have methods called against a single object instance concurrently from multiple threads), but am having trouble finding such a description in the JDK javadocs static that fact.
    I'm assuming that all thread-specific 'state' would be managed by the Object target passed to methods like invoke()/get()/set() and not on the actual Field and Method objects themselves. Ideally, i'd like to only have to look up fields and methods only once reflectively, and thereafter just use the same reflection object instances to access their target objects at runtime as a performance optimizations - possibly in different threads and at the same time - without having to pay the cost of looking it up again. I should be able to do that providing Method.invoke() is thread safe. Otherwise, i'd probably be forced to call Class.getMethod() to get a new Method object to use against each object instance, which would be more costly both from a memory standpoint (more Method objects) and a lookup-cost perspective.
    Given that lots of existing performance-critical enterprise infrastructure code, such as OR database APIs, IoC frameworks and J2EE containers use reflection to decouple the generic code from any app specific code (from a compile time perspective) as an alternative to code generation, it's surprising that there's no obvious statement about thread safety in these classes. If I look at the source code for Method, it appears to be thread safe, but I can only get so far with this analysis, as the critical code in Method appears to be implemented using a class named 'sun.reflect.MethodAccessor', whose source I don't have access to.
    I know it's possible to invoke a method against multiple objects by calling Method.invoke() against each of the target objects in question. However, there's no mention as to whether it's safe to use a single Method object instance to invoke a method against multiple target object instances at the same time (i.e., from different threads running in parallel). This would fail, for instance, if the Method object had data members that were used to communicate information between internal calls without any synchronization, as the values might be used by one thread while another was changing them.
    Just to clarify (as i've seen some confusion in other forum discussions on this topic):
    I completely understand that the thread safety of a target object's method (read, small 'm') is entirely dependent upon it's implementation and not the mechanism by which it's invoked - i.e., whether a method is invoked by an explicit compiled-in call against an instance of the target object in some Java source file, or indirectly via Method object-based reflection, is immaterial the the method's thread safety.
    What i'm asking about is the thread safety of the Method.invoke() call itself (read, big 'M'). Same question wrt Field.get()/.set() as well. These calls should be thread-safe if they're stateless wrt the Method and Field object instances that they are invoked against.

    In general, if a Java API is silent about multi-threading, it is intended to be thread-safe. See the javadoc for HashMap for an example of an explicit warning.
    It is true that Java code can have bugs that show up only on unusual implementations of the Java memory model, such as relaxed memory model machines. Most (if not all) implementations of the JDK have been deployed principally on platforms with strong memory models. (Perhaps not coincidentally, those are also the machines that have market share.) There are even bugs found occasionally in the JDK core, so draw your own conclusions about the bug-tail of our software stack on systems with relaxed memory models!
    One of the more likely bugs to run into on highly optimized systems is failure of timely initialization of non-final fields in objects which are shared in an unsynchronized manner. See http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight and related pages. JDK core programmers (at Sun, to my personal knowledge) take care not to write code with such bugs, but application programmers might.
    And, yes, caching your own Method objects is a good idea, if only because their lookup is generally cumbersome and slow. If you are very performance sensitive, you'll end up generating bytecode "shim" between your callers and the desired target methods. I expect that the http://openjdk.java.net/projects/mlvm/ (an openjdk project we are just starting) will provide some relief for this; stay tuned.
    Finally, since Method objects have no state to speak of (except their "accessible" bit, which is an ahead-of-time configuration), it would be really, really surprising if they could create a race condition of some sort. If you expect race conditions in formally stateless data structures, you are certifiably paranoid. (A normal state on some platforms, hopefully not on Java.)
    For more information about method calls, including reflective methods, see my blog post: http://blogs.sun.com/jrose/entry/anatomy_of_a_call_site
    Best wishes...

  • ClassCastException - While type casting Home object after EJB JNDI Lookup

    Sun One Application Server throws a ClassCastException when I try to type cast Home object to it's respective interface type.
    Here is the code ---
    ==============================================
    Object obj = PortableRemoteObject.narrow( context.lookup( jndiName ), homeClass);
    System.out.println("Remote Object - obj : "+obj);
    if (obj != null) {
       System.out.println("obj.getClass().getName() : "+obj.getClass().getName());
       System.out.println("obj.getClass().getSuperclass() : "+obj.getClass().getSuperclass());
       Class[] interfaces = obj.getClass().getInterfaces();
       if (interfaces != null) {
          for (int count = 0; count < interfaces.length; count++) {
             System.out.println("interfaces[ " + count + " ].getName() : " + interfaces[ count ].getName());
    }==============================================
    The class name is dislpayed as the Stub class name.
    While displaying the interfaces, the Home Interface name is displayed.
    But later when I try to type cast it into Home Interface type, it throws a ClassCastException.
    Can somebody please check this?

    Please post the stack trace. Also, take a look at our EJB FAQ to make sure you're doing the
    recommended lookup :
    https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html

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

  • Casting webservice Objects

    I've got a question about Webservices in Flex. When using the 'Import Web Service'-command, Flex automatically creates the appropiates Classes and Connection scripts. When using these scripts, Flex automatically casts Objects received by a Webservice to a Strong-typed Class, and not a ObjectProxy. This is very handy. The only downside of this features is that you'd have to recreate all the files when you change a property in your webservice. Because I had to make manual changes in the generated files, everytime I make a change in my Webservice, I have to update all these files again. Therefor I would like to make my own connectionscripts, so when my webservice changes, I only have to make this change in my Flex-classes. Problem is I couldn't find any scripts that correctly connects to a Webservice, AND casts my objects to a Strong-typed class. Everytime I try to cast a received ObjectProxy to a certain Class, I get null returned. I've tried several things, including the SoapDecoder, and the SchemaRegister, but I somehow can't get it to work.
    Does anybody has an example of a script that does this job or know how to get this done?
    Thanx,
    Paul

    Hi Mike,
    Thank you for your response. Yes, I was trying to cast the elements returned from
    examineHeaderElements to SOAPHeaderElement. This was throwing a ClassCastException.
    Now, I am using
    soapHeader.getChildElements(nodeName)
    This seems to work fine. Where I created the nodeName through SOAPEnvelope's createNode()
    method. Don't know what the original problem was. But, now I avoided using that
    API. Will let you know if I get any more information.
    Regards,
    Adam
    "Michael Wooten" <[email protected]> wrote:
    >
    Hi Adam,
    The java.util.Iterator returned from the examineHeaderElements() method,
    should
    contain javax.xml.soap.SOAPHeaderElement objects. Is that what you are
    trying
    to cast to?
    Regards,
    Mike Wooten
    "Adam Athimuthu" <[email protected]> wrote:
    Hello,
    I am getting a ClassCastException when trying to process the SOAPHeader
    in a SOAP
    handler. I tried the following...inside the handleRequest(MessageContext
    context)
    method:
    SOAPPart soapPart=null;
    SOAPEnvelope soapEnvelope=null;
    SOAPHeader soapHeader=null;
    SOAPMessageContext soapContext=(SOAPMessageContext) context;
    System.out.println("handleRequest");
    SOAPMessage soapMessage=soapContext.getMessage();
    System.out.println("SOAPMessage: "+soapMessage.toString());
    try
    soapPart=soapMessage.getSOAPPart();
    soapEnvelope=soapPart.getEnvelope();
    soapHeader=soapEnvelope.getHeader();
    System.out.println("SOAPHeader: "+soapHeader.toString());
    soapHeader.addTextNode("CustomNode");
    Iterator allHeaders=soapHeader.examineHeaderElements("http://someuri.com");
    The examineHeaderElements throws a ClassCastException, no matter what
    method gets
    invoked on the soapHeader object. I tried casting this to the weblogic.webservice.core....
    implemented objects. The result is the same.
    I appreciate any help.
    Thanks,
    Adam
    Athi D. Athimuthu

  • 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 Class object

    Hi,
    I would like to cast an object type Class to another type, eg. MyAdapterClass. I can not figure out any way of doing so, so help is highly appreciated...
    Thanx, Flo!
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    Class classTemp = cl.loadClas("MyAdapterClass");
    // something similar to the line below is required..
    // MyAdapterClass mac = (MyAdapterClass)classTemp;

    Multi-post
    http://forum.java.sun.com/thread.jspa?threadID=754736
    @Op. Please don't create several threads with the same question.
    Kaj

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

  • Class cast exception while casting FTPConnectionFactory object

    Hi
    I have SOA Suite Advanced installation - 10.1.3.4 MLR#5.
    I have developed a BPEL which polls an FTP site using a JCA FTPConnectionFactory registered in JNDI - eis/Ftp/My_Ftp.
    If file is present, then BPEL doesnt fetchs it... instead calls a java program through WSIF binding.
    In java program i am retrieving the JNDI object - eis/Ftp/My_Ftp.. casting it to oracle.tip.adapter.ftp.FTPConnectionFactory and get the FTP host and credentials.
    Now using those details i mannually create an FTP Connection and retieve the file.
    This program worked for sure... but recently when i tried the same i got the ClassCastException while casting java.lang.Object got from JNDI to oracle.tip.adapter.ftp.FTPConnectionFactory. I havnt changed any thing on server since... could not understand why this issue has cropped now.
    After lot of research the issue seems due to different Classloaders. JNDI object was loaded by ClassLoaderA and in my java program it is being loaded by ClassLoaderB.
    And these two classloaders dont share classes with each other.
    This is the code:
    InitialContext ctx = new InitialContext();
    Object jndiFTPObj = ctx.lookup("eis/Ftp/My_Ftp");
    System.out.println("Got Object from JNDI is: "+jndiFTPObj+" ClassLoader - "+jndiFTPObj.getClass().getClassLoader());
    // it prints -- Got Object from JNDI is: oracle.tip.adapter.ftp.FTPConnectionFactory@1aa3bbc ClassLoader - FtpAdapter:0.0.0
    FTPConnectionFactory ftpConF = (oracle.tip.adapter.ftp.FTPConnectionFactory)jndiFTPObj;
    // here i get error -- java.lang.ClassCastException: oracle.tip.adapter.ftp.FTPConnectionFactory
    Thinking of RMI/IIOP i even tried:
    FTPConnectionFactory ftpConF = (FTPConnectionFactory)PortableRemoteObject.narrow(ctx.lookup("eis/Ftp/My_Ftp"), FTPConnectionFactory.class);
    it didnt solve the error.
    I tried loading the class using the same loader as:
    Class.forName("oracle.tip.adapter.ftp.FTPConnectionFactory",true,jndiFTPObj.getClass().getClassLoader());
    even that didnt solve the error.
    If any body has some idea... pls help
    Thanks
    Inder

    Issue was due to ClassLoaders... tried to use the same classloader... but couldnt.
    Eventually solved it by using Java Reflection.
    Thx

  • How to cast an object in JSF?

    I am working on a travel application. A user can have several bookings and a booking can have several components. A component can be either air or hotel. I want to list the user's bookings on the client using JSF datatable.
    <h:dataTable var="component" value="#{booking.components}">
    Now depending upon the class of component I need to present different information.
    My question is how to cast the variable in JSF ?
    Thanks

    You can use the String value of Object#getClass()#getName() to lookup the classname and evaluate it in the 'rendered' attribute.
    Basic example:
    package mypackage;
    public class Animal {}
    package mypackage;
    public class Cat extends Animal {}
    package mypackage;
    public class Dog extends Animal {}
    package mypackage;
    public class Fish extends Animal {}MyBeanpublic List<Animal> getList() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Fish());
        return animals;
    }JSF<h:dataTable value="#{myBean.list}" var="item">
        <h:column>
            <h:outputText value="It's a Cat" rendered="#{item.class.name == 'mypackage.Cat'}" />
            <h:outputText value="It's a Dog" rendered="#{item.class.name == 'mypackage.Dog'}" />
            <h:outputText value="It's a Fish" rendered="#{item.class.name == 'mypackage.Fish'}" />
        </h:column>
    </h:dataTable>As far there is no way to cast objects in JSF.
    Edit
    If you find it useful, move the classname request to the superclass:
    public class Animal {
        public String getType() {
            String className = getClass().getName();
            return className.substring(className.lastIndexOf('.') + 1);
    }Which makes life easier without struggling with package names:<h:outputText value="It's a Cat" rendered="#{item.type == 'Cat'}" />
    <h:outputText value="It's a Dog" rendered="#{item.type == 'Dog'}" />
    <h:outputText value="It's a Fish" rendered="#{item.type == 'Fish'}" />Message was edited by:
    BalusC

Maybe you are looking for