The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
September 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Dynamically Typecasting or Narrowing on an object at Runtime

Posted by Michael Walters on September 18, 2000 at 12:14 PM

Suppose you have:

Base class: A
Classes derived from A: B, C, and D

You have a factory class (Factory.create(String className) ) that will return an instance of a B, C, or D if it is passed the class name.

Usually if you want to narrow on the object coming back, you'd do a typecast:
B b = (B)Factory.create("B"); , but this done only at compile time.

However, I'd like to narrow on the object at runtime instead of comile time.

Do you know how that might be done?

What I'd like is a way where I could specify in a string, the type of object I'm expecting back and still maintain the subclassed reference when it does get returned.

To recap, I could create a dynamic reference variable that
would hold the dynamically typecast'd object being returned
from the factory method.

Unless I'm mistaken, this appears to be the only thing missing in the Reflection API.

Thanks,
Mike



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us