Nigel Thomas
Nigel Thomas

Reputation: 1929

How to check which class invoked a method

I need to get the name of the class in an over-ridden method which has called the method

How can it be done?

Upvotes: 1

Views: 352

Answers (3)

Cisco
Cisco

Reputation: 532

You can get the class with:

class.getMethod("your_over-ridden_method_name").getDeclaringClass();

For example:

System.out.println(class.getMethod("your_over-ridden_method_name") + " declared by " + class.getMethod("your_over-ridden_method_name").getDeclaringClass());

Upvotes: 2

Achintya Jha
Achintya Jha

Reputation: 12843

Throwable t = new Throwable(); 
StackTraceElement[] elements = t.getStackTrace(); 

Class StackTraceElement has various methods like

String calleeMethod = elements[0].getMethodName(); 
String callerMethodName = elements[1].getMethodName(); 
String callerClassName = elements[1].getClassName(); 

Upvotes: 4

u25891
u25891

Reputation: 611

You can get the class of the current object inside your method using this.getClass(), or use Thread.currentThread().getStackTrace() to walk the call path.

Upvotes: 3

Related Questions