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:

dynamic typecasting alternative

Posted by rabiraj on June 13, 2001 at 6:07 AM

This is an alternate solution. See if it helps you.

Class myClass = Class.forName(B);
Object obj = Factory.create("B");
Object obj1 = myClass.newInstance();
obj1 = obj;

now from obj1, u can access all the fields and the methods of class B.

> 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