Re: How do I find the runtime class of calling object from a static method?

From: Tim Jowers (timjowers_at_yahoo.com)
Date: 12/18/03


Date: 17 Dec 2003 17:03:25 -0800


"Sean Knapp" <sknapp@nospamplease.com> wrote in message news:<bro1io$qje$1@news.Stanford.EDU>...
> Okay, here is the setup:
>
> Class A has a static method foo, and a normal (non-static) method bar. foo
> is called by bar. In foo, I need to find the actual class of the object that
> just called me.
>
> The tricky part is this: Class A has dozens of sub-classes, all of which use
> the method bar, but never overide it.
>
> The code looks like this:
>
> class A {
> public void bar() {
> foo();
> }
>
> static public void foo() {
> // Find calling class type
> }
> }
>
> class B extends A {
> }
>
> class C {
> public static void main(String[] args) {
> new A().bar();
> }
> }
>
> I know about the SecurityManager.getClassContext() trick which works great,
> except for this case, since class B never shows up on the stack trace
> because it's superclass method is called.
>
> I know I could also simply pass in the class object from this.getClass() in
> bar, but I have dozens of these methods and would much prefer a more elegant
> solution that multiple wrapper classes.
>
> As far as I can figure, it seems I need to somehow get the corresponding
> objects to these classes found on the stack in order to use the getClass()
> method, but am completely stuck as how to do this.
>
> If anybody has any insight into this, please let me know, you'll make my
> month!
>
> Thank you in advance!
> Regards,
> Sean Knapp

Sean, what does the keyword "this" refer to?