aspose file tools*
The moose likes Java in General and the fly likes How to get the class name of the subclass from a static method in the superclass? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get the class name of the subclass from a static method in the superclass?" Watch "How to get the class name of the subclass from a static method in the superclass?" New topic
Author

How to get the class name of the subclass from a static method in the superclass?

Philippe Desrosiers
Ranch Hand

Joined: Mar 29, 2006
Posts: 138
I have the following:


Needless to say, the example is drastically over-simplified, but basically, as-is, the whatsMyClass method returns the Subclass, which is what I want. But I also want to be able to specify the whatsMyClass method as static. Is there any way to do this?

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Nope. getClass() needs to be called on an object of the given class; a static method has no such object available.

Put another way: a static method can't determine "the class you called it on."


[Jess in Action][AskingGoodQuestions]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39814
    
  28
And a superclass has no notion about what subclasses have been created.
Philippe Desrosiers
Ranch Hand

Joined: Mar 29, 2006
Posts: 138
Yeah, the closest I came was throwing an exception, then examining the StackTraceElement array for the throwing class, but even that gives the Superclass...

Oh well.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Philippe Desrosiers wrote:Yeah, the closest I came was throwing an exception, then examining the StackTraceElement array for the throwing class, but even that gives the Superclass...

Oh well.


I can't think of a way to do it 'automatically' but you can do it with some method calls:

Add some error checking to make sure the class was set and you at least have a starting point. Here would be an example of when it might be used:




Steve
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to get the class name of the subclass from a static method in the superclass?