• Post Reply Bookmark Topic Watch Topic
  • New Topic

Determine Superclass  RSS feed

 
Lee Barney
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have several classes that inherit from other super classes. I have objects in a list and need to be able to determine which superclass they inherit from so I can make the appropriate calls. How can I examine the inheritance tree at run time to find this out?

I know .getClass() only returns the final subclass.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Class.getSuperclass() if you really need to be looking at Class objects, or otherwise simply using the "instanceof" operator would probably do you.
 
Ryan McGuire
Ranch Hand
Posts: 1143
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Use Class.getSuperclass() if you really need to be looking at Class objects, or otherwise simply using the "instanceof" operator would probably do you.


BUT...
Using instance is often a red flag that you should rearrange your class hierarchy and move some specific functionality into subclasses.

For instance, say you have top level (one level below Object) classes Salaried and Hourly. Manager, Engineer, and Programmer subclass Salaried, while Technician and Janitor subclass Hourly.

If you have code like like...


Then you should define a (perhaps abstract) super class for Salaried and Hourly that defines that functionality in a more generic way. That way, the above code would get condensed into just...

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!