• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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."
 
Marshal
Posts: 79180
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:


 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic