Get your CodeRanch badge!*
The moose likes Java in General and the fly likes determine class info at runtime Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "determine class info at runtime" Watch "determine class info at runtime" New topic
Author

determine class info at runtime

manish ahuja
Ranch Hand

Joined: Oct 23, 2003
Posts: 312
Hi All,

I want trap the class name of an incoming object.
Here is the scenario
I have a super class Parent & have 5 derived classes which extend Parent say Child1, Child2, Child3 , Child4, Child5.

Now the child(n) object is sent to me after doing an upcast.
Parent p = new Child1();
It could be an instance of Child2 , or Child3 so on

Now in my code I want to determine what is the type of the Child class object by using the Parent reference (p) as mentioned above.

Is there a way to do that without resorting to the (instanceof) operator.
Say in a scenario where in I dont know what all subclasses does the Parent class have so I can avoid all the numerous if conditions.



Do post your thoughts on the same


Regards
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
Calling "p.getClass().getName()" will give you a String with the class name.


Ping & DNS - updated with new look and Ping home screen widget
Nicole Lacoste
Ranch Hand

Joined: Oct 04, 2006
Posts: 30
Hi,

"p.getClass().getName()" is an example of reflection.
There is a great tutorial on the sun web site, http://java.sun.com/docs/books/tutorial/reflect/index.html, which you might want to look at for more details. You can do lots of very nice stuff with reflection, like find out what methods and ctors are available of your unknown class.

Niki
Lucas Lee
Ranch Hand

Joined: Oct 02, 2006
Posts: 53
Using getClass().getName() will work.
But I still wonder if you are trying to use a wrong way ,if you should implement some logic in every child classes rather than do it using reflection.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: determine class info at runtime
 
Similar Threads
How to control no. of Child Windows
Polymorphism reference variable question
Can JAXB handle Polymorphism
Best way to join a parent with many child tables yet preserving all parent table rows
Very interesting point in inheritance