| 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: 24057
|
|
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: 32693
|
|
|
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: 3036
|
|
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
|
 |
 |
|
|
subject: How to get the class name of the subclass from a static method in the superclass?
|
|
|