Home arrow static arrow Java Programming [Archive] - Reflection and RTTI
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Reflection and RTTI
This topic has 2 replies on 1 page.

Posts:2
Registered: 6/30/00
Reflection and RTTI  
Aug 4, 2004 6:29 AM



 
I need to create references to new objects of leaf classes from the root class in a class hierarchy. I am not sure how to do this. I have considered reflection and RTTI, but with no success.

I have a hierarchy of classes with several levels. Each class has methods that overrides the methods it inherited. Each of the classes at the bottom of the hierarchy, has a different code for the methods inherited. The root class does not know the existence of the classes at the bottom of hierarchy. The root node receives a "token" from an external source. Based on this "token" (it is a String) it needs to generate a reference to the Object of the class for the "token". Then the root class can apply one of its methods on this reference. This application of method needs to give different results for different references.

I tried the following approaches. I applied Class.forName(token) to get the Class of the "token". Then I used newInstance() on this Class. An Object refers now the instance. I needed to type cast this object to apply my method to get the desired result. Since I do not know the type of the object, and the class of the object is not loaded at the compile time, I decided to use reflection. I applied getConstructors(), getClass(). Still the problem of type casting to the type of the required class remains unaddressed. Can anyone help? Thanks!
 

Posts:10,972
Registered: 10/23/03
Re: Reflection and RTTI  
Aug 4, 2004 6:36 AM (reply 1 of 2)



 
public abstract class Animal {    public abstract void vocalize();     public static Animal create(String name)        throws ClassNotFoundException, InstantiationException, IllegalAccessException {        return (Animal) Class.forName(name).newInstance();    }     public static void main(String[] args) throws Exception {        create("Dog").vocalize();        create("Cat").vocalize();    }} class Dog extends Animal {    public void vocalize() {        System.out.println("woof");    }} class Cat extends Animal {    public void vocalize() {        System.out.println("meow");    }}
 

Posts:2
Registered: 6/30/00
Re: Reflection and RTTI  
Aug 4, 2004 1:26 PM (reply 2 of 2)



 
Thanks a million! It worked!
 
This topic has 2 replies on 1 page.