Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Philippe Desrosiers
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And a superclass has no notion about what subclasses have been created.
 
Philippe Desrosiers
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic