What's my Class name ?

How can a super class method know the name of the extending sub class that is calling that method ? For example in the following code excerpt, I always get Class: SuperClass Regards -- public class SuperClass { public method whichSubClass() { System.out.println("Class: " + getClass()); } } public class SubClass extends SuperClass { ... whichSubClass(); ... }

getClass() will return the "runtime class". The following example will return the subclass name. see if it helps.

If this doesnt answer your question, paraphrase your question

Richard Grey
Greenhorn

Joined: Nov 21, 2001
Posts: 25

posted Dec 11, 2001 10:19:00

0

Thanks Rex, Your code is in fact the same as mine, both of which work. Problem is, I didn't understand/couldn't phrase what I wanted to say myself! What I am trying to ask is: Can I tell in class A's method which other class (say B) has instantiated the instance of class A and called that method on Class A ? So, Class B instantiates Class A and calls A.method(). Can A.method() somehow tell and report that Class B has called it ? B does not extend or relate to A in any way. Cheers

Rex Rock
Ranch Hand

Joined: Jun 25, 2001
Posts: 82

posted Dec 11, 2001 10:52:00

0

I don't know any direct way of getting this done, but there is a workaround..however this might not be best suited for your needs. You can make ur method in class A to accept one more argument of type "Object", and in class B when u call the method, send "this" as parameter, and then u can use getClass()

[This message has been edited by Rex Rock (edited December 11, 2001).]

Richard Grey
Greenhorn

Joined: Nov 21, 2001
Posts: 25

posted Dec 12, 2001 04:44:00

0

Thanks Rex, I did this (the obvious way) earlier - just thought that it would be nice if the method could sort of work the calling class out itself. It would abstract the need away from our developers, helping to standardise things (like logging, hence the need). The more we can abstract away, the "more common" everything becomes !! Cheers.