aspose file tools*
The moose likes Java in General and the fly likes Reflection and Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reflection and Casting" Watch "Reflection and Casting" New topic
Author

Reflection and Casting

Ayyappan Selvaraj
Ranch Hand

Joined: Sep 20, 2004
Posts: 63
I use reflection to invoke a method... I define a super class(StubImpl) object and by invoking a method of another class, which returns the sub class(CodesServicePortType_Stub) object instantiation for this super class object. And its required that I should cast the subclass object to instantiate the super class object. And this casting i want to be done dynamically. I know the name of the sub class(CodesServicePortType_Stub). What shud be done??

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Let's see if I'm reading you right. In this line:

you'd like to have the type you are casting to more dynamic? There's a two part answer - you can't, and you don't need to. What type did you declare the variable "binding"? Just cast to that type. The cast and assignment will work fine with any subtype of StubImpl returned by the getCodesServicePort() method.

Now if you need to call methods on CodesServicePortType_Stub that are not defined on StubImpl, we should maybe revisit the design and see why you're doing that.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ricky Clarkson
Ranch Hand

Joined: Jul 27, 2006
Posts: 131
Casting doesn't actually create or change anything at runtime, it just performs a check. The compiler must know what methods your objects have at compile time. Trying to cast to some dynamically-known type won't help. Learn how Java does OOP.
Ayyappan Selvaraj
Ranch Hand

Joined: Sep 20, 2004
Posts: 63
Stan James,
The cast and assignment will work fine with any subtype of StubImpl returned by the getCodesServicePort() method.

I understand this and it works fine.. The getCodesServicePort() method returns an object of CodesServicePortType_Stub and when I change the code as

binding = (StubImpl) theMethods[i].invoke(service, null);

the binding object is of CodesServicePortType_Stub and not the StubImpl and am able to call a method which is available in CodesServicePortType_Stub.


Ricky Clarkson,
And am still learning how JAVA does OOP. thanks for pointing it..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reflection and Casting