Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reflection and Casting

 
Ayyappan Selvaraj
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic