Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Know the class that invoked a method

Posted on 2002-06-09
6
Medium Priority
?
193 Views
Last Modified: 2013-11-23
Hi!
Is there a way to know which class called a method?
For example, if I have a method in an object: toString(), can I know which object called me?
0
Comment
Question by:rzvika2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 1

Expert Comment

by:BaneBane
ID: 7065257
This is messy but you could probably extract the information from the stacktrace.

Hope this helps.
0
 
LVL 35

Expert Comment

by:girionis
ID: 7065509
 As BaneBane suggested you can do it by processing the call stack printed to a stream by the printStackTrace() method.

  For a complete example with source code take a look here:

http://developer.java.sun.com/developer/qow/archive/104/

  Hope it helps.

0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 800 total points
ID: 7066364
my example from the PAQ

(some time ago, I have created special utility class for this purpose but I can't find it on my workstation right now)

*****

public class test
{
public static void main(String args[])
{
 demo obj = new demo();

 obj.doIt();
 demo1.staticDoIt();
}
}

class demo1
{
     public static void staticDoIt()
     {
           b bObject = new b();
           bObject.doIt();
     }
}
class demo
{
   
public void doIt()
{
 b bObject = new b();
 bObject.doIt();
}
}

class b
{
public void doIt()
{
try {
throw new Exception();
} catch (Exception e)
{
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     PrintStream ps = new PrintStream (bos);
     e.printStackTrace(ps);
     ps.close();
     String st = new String (bos.toByteArray());
     st = st.substring(st.indexOf("at") + 3);
     st = st.substring(st.indexOf("at") + 3);
     int n = st.indexOf(".");
     String objName = st.substring(0, n);
     st = st.substring(n + 1);
     n = st.indexOf("(");
     String methodName = st.substring(0, n);
   
     System.out.println("b.doIt() was called from object of class (class) " + objName + ", method " + methodName);
}

}
}
0
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
LVL 4

Expert Comment

by:seguret
ID: 7066536
If you have the JDK 1.4, you don't have to use all those parsers anymore : look at the StackTraceElement classe !

All what you have to do is to call  Throwable.getStackTrace(). It returns an array of StackTraceElement. On those elements, you can call the getClassName method.
0
 
LVL 2

Expert Comment

by:xxMariusxx
ID: 7067851
new Throwable().printStackTrace();
0
 
LVL 9

Expert Comment

by:doronb
ID: 7070524
Hello,


You could try and use some Java reflection and the following code:
_________________________________
import java.lang.reflect.*;

// Class and other code declarations

// Static method to find out which class called our method..
     private static Method sysGetCallerClass;

     static {
          try {
               sysGetCallerClass = System.class.getDeclaredMethod("getCallerClass", null);
               sysGetCallerClass.setAccessible(true);          } catch (Exception ex) {
               ex.printStackTrace();
          }
     }

// More class and code declarations

// Then in any method you want to know the calling class use:
          Class callingClass = null;
          try {
               callingClass = (Class)sysGetCallerClass.invoke(null, null);
          } catch (Exception ex) {
          }
// WARNING: COPY THE ABOVE CODE TO EVERY METHOD THAT NEEDS TO KNOW THE CALLING CLASS, THIS CODE CANNOT BE IN ITS OWN METHOD SINCE IT WILL REPORT ITS OWN CLASS AS CALLING ITSELF.

// NOTE: This code makes use of an un-documented method in the class java.lang.System, this method might one day completely disappear so using this code might be rendered useless in the future.

Hope this helps

Doron
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question