1

Is it possible how to know which method call another dynamically?.

See below:

class a { public void one(){ System.out.println(methodWhoCallsVoidOne().getName()); } public void two(){ this.one(); } } 
2
  • Why do you need it? If it changes the methods behaviour, can't you control that using variables that you pass to it? Commented Dec 3, 2010 at 22:32
  • By the way, you don't need to put this in front of method invocations. Commented Dec 4, 2010 at 4:25

4 Answers 4

6

Not without hacking around with creating exceptions and pulling the stacktraces out of them.

I would question why you want to do this? In the past when people have asked this it has almost always been a sign of a bad design somewhere.

Sign up to request clarification or add additional context in comments.

Comments

2

Or you can use Thread.currentThread().getStackTrace()

1 Comment

That still creates a throwable internally and is rather expensive, but it does work for the most part
0

You can get a stacktrace:

new Throwable().getStackTrace() 

It returns an array of all callers from the first one.

Comments

0

If you are using an IDE such as Eclipse, you could place a break point and look at the call stack. Quck google search on java call stack, turned up this:

public class WhoCalledMe { public static void main(String[] args) { f(); } public static void f() { g(); } public static void g() { showCallStack(); System.out.println(); System.out.println("g() was called by "+whoCalledMe()); } public static String whoCalledMe() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); StackTraceElement caller = stackTraceElements[4]; String classname = caller.getClassName(); String methodName = caller.getMethodName(); int lineNumber = caller.getLineNumber(); return classname+"."+methodName+":"+lineNumber; } public static void showCallStack() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (int i=2 ; i<stackTraceElements.length; i++) { StackTraceElement ste = stackTraceElements[i]; String classname = ste.getClassName(); String methodName = ste.getMethodName(); int lineNumber = ste.getLineNumber(); System.out.println(classname+"."+methodName+":"+lineNumber); } } } 

1 Comment

Thhhx!! =)... you gave a pair of ideas

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.