Solved

Know the class that invoked a method

Posted on 2002-06-09
6
166 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
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 200 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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Basics of Drool Rule Engine with few samples 2 41
@SBGen Method 3 25
backtracking recursion  code 19 40
eclipse java  build path 6 20
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now