oop - Finding type of the class which is calling a method in Java -


this question has answer here:

i'd know what's type of object calling method in class in java, e.g. :

 class a{    public a(){      //..    }    public void method1{       //here i'd find what's type of object calling method     }   }    class b{     public b(){       a = new a();       a.method1();      }    }    class c{      public c(){         a = new a();         a.method1();      }    } 

you can inspecting stack upon method call code. check out thread.getstacktrace() , use current thread returned by

thread.currentthread() 

you can work way stack trace array , determine chain of callers. note caveat in documentation however:

some virtual machines may, under circumstances, omit 1 or more stack frames stack trace. in extreme case, virtual machine has no stack trace information concerning thread permitted return zero-length array method.

if need find out called subset of classes, change classes such implement caller/callee interfaces , implement method signatures thus:

public void dosomething(..., caller caller); 

where calling class implements caller. way you're enforcing relatively type-safe method calls , parameter passing.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -