2

I need an suggestion on this

 class A{
    B b;
 }

 Class B{
    P String  something();
 }

In

 class test{
    B b = new B();
    b.something();
 }

something()

must return the name of the cal-lee class its like if somebody calls me(by name) I should know his name.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241

3 Answers3

6

A solution is to programmatically generate a stack trace:

private static String getCallerName() {
    StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
    for (int i=1; i<stElements.length; i++) {
        StackTraceElement ste = stElements[i];
        if (!ste.getClassName().equals("B") && ste.getClassName().indexOf("java.lang.Thread")!=0) {
            return ste.getClassName();
            // you could also use ste.getMethodName() or ste.getLineNumber()
        }
    }
    return null;
}

You would use it like this, for example :

public void something() {
   System.out.println("called by " + getCallerName());
}
Edward Samson
  • 2,395
  • 2
  • 26
  • 39
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

If somebody calls you by name, you wouldn't know it, unless that somebody already told it to you.

Same thing here.

Pass your name from class A to class B.

Allan Spreys
  • 5,287
  • 5
  • 39
  • 44
  • ya ,i should not know it.But my requirement is to know the person calling me.Thanks for giving a different look to the problem. – user2143318 Mar 11 '13 at 06:20
0

As the problem seems a bit extraordinary, an architectural alternative. Whether it fits better I do not know.

class A {
    class C extends B {
        String something() {
            ... A.this
        }
    }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138