0

I'd like to know what's the type of the object which is calling a method in another class in Java, e.g. :

 class A{
   public A(){
     //..
   }
   public void method1{
      //here I'd like to find what's the type of the object which is calling this method 
   }
  }

  class B{
    public B(){
      A a = new A();
      a.method1();
     }
   }

  class C{
     public C(){
        A a = new A();
        a.method1();
     }
   }
Arian
  • 7,397
  • 21
  • 89
  • 177
  • 2
    the only thing that comes to my mind is to throw an exception and analyze the stacktrace, but that would be a horrible practice – Marco Forberg May 14 '13 at 14:39
  • It's less horrible if you simply instantiate the exception. You don't need to throw it. But you can interrogate the current thread for its stack instead – Brian Agnew May 14 '13 at 14:43
  • 1
    Why do you need to know this? I'm vaguely horrified at what you could possibly be doing that can't be accomplished by passing in some sort of enum flag instead. You're going to create some very brittle, tightly coupled code. – Thorn G May 14 '13 at 15:03
  • Enum flag ? Why not pass in the reference to the calling class in the method parameters ? – Brian Agnew May 14 '13 at 15:04
  • So how are going to define it in the method parameters as you don't have prior knowledge about the class of that input parameter ? – Arian May 14 '13 at 17:26

2 Answers2

4

You can do this by inspecting the stack upon the method call to your code. Check out Thread.getStackTrace() and use the current thread as returned by

Thread.currentThread()

You can work your way back up the stack trace array and determine the chain of callers. Note the caveat in the documentation however:

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

If you need to find out who called you for a subset of your classes, I would change the classes such that they implement some Caller/Callee interfaces and implement method signatures thus:

public void doSomething(..., Caller caller);

where your calling class implements Caller. That way you're enforcing some relatively type-safe method calls and parameter passing.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

Try this:

Thread.currentThread().getStackTrace()
Farlan
  • 1,860
  • 2
  • 28
  • 37