In the snippet code below Object obj = null; String ss = new String("test"); obj = ss; String ss2 = (String) obj; ^ Where ^ denote the type casted to. Is there anyway to provide the type at run time dynamically?
Hi Frank, Yep. It's called reflection. Look at the API documentation on class Class. There is a method named getClass() in Object that returns an instance of Class. The Class class has methods to create new instances; discover properties, constructors, and methods; get super classes; etc. Of course this is a whole lot tougher coding than a simple typecast . Hope this helps Michael Morris SCJP2
Originally posted by Ilja Preuss: I can't think of any reason to need a "dynamic type cast". Could you please explain what you want to do?
I have been working on a project which can convert between an XML string and java class. I need to dynamically cast xml node names into a java class if it is an object. [ April 14, 2002: Message edited by: bill william1 ]
Originally posted by Ilja Preuss: I can't think of any reason to need a "dynamic type cast". Could you please explain what you want to do?
My question originated from a need to invoke a entity bean dynamicly. As you know, a homeinterface.findByPrimaryKey() returns a remote interface that requires a explicit type cast. What if which bean should be invoked can only be known at run time? Using reflection can be a alternative. Anything else?
Hello Morris & Fin, Can you please tell me how is it possible using Reflection. Using getClass() you can get a "Class". With this class object we can 1. Create a instance of the object represented by the class using class.newInstance() 2. or get the name of the class using class.getName(). But this string containing the name cannot be substituted for casting. Say, A = "String" String str = (A)obj;
My question originated from a need to invoke a entity bean dynamicly. As you know, a homeinterface.findByPrimaryKey() returns a remote interface that requires a explicit type cast. What if which bean should be invoked can only be known at run time? Using reflection can be a alternative. Anything else?
I don't know wether there are any pitfalls when using EJBs, but the "normal OO solution" would be to use polymorphism for this. That is, let all appropriate classes implement a common interface, cast to this interface and call a method of the interface. Something along the lines of: