Home arrow static arrow Java Programming [Archive] - Question about reflection
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Question about reflection
This topic has 4 replies on 1 page.

Posts:68
Registered: 03-12-11
Question about reflection  
Jul 15, 2004 6:40 AM



 
This is kind of a strange question, and so I don't know quite how to word this. For backgroundwiki/./, I am trying to write a debugging utility class. Is there a way to determine which class and method are calling a specific method of a debugging class object? Let me show you what I mean.

Say we have the following code:

class MyClass {     void myMethod {         Debugger d = new Debugger();        d.logAction();         ....    }}

Is there a way within the logAction method to determine the class the debugger is running in, and which method is calling the logAction method of the debugger? I would like to do this, without specifically telling the debugger.
 

Posts:428
Registered: 26.06.00
Re: Question about reflection  
Jul 15, 2004 7:16 AM (reply 1 of 4)



 
You can't use reflection,

you can create a new Throwable and use getStackTrace() (since 1.4) which returns a StackElement[] which contains your stacktrace from which in turn you can parse what your calling class is.
Just a suggestion.
 

Posts:3,055
Registered: 18/06/98
Re: Question about reflection  
Jul 15, 2004 7:21 AM (reply 2 of 4)



 
a) Learn to use the log4j package ( http://logging.apache.org/log4j/docs/index.html ), it does exactly what you want to do. You can download and study its source code. Knowing log4j is a must for every Java programmer that works with J2EE - it is THE standard.
b) If you're using JDK 1.4 or later, and you really want to write your logging class, you can use the class java.lang.StackTraceElement (check the javadoc). It is easier to use than the method that Log4J used for determining the method and class - it is because Log4J must run in older JDK versions.
 

Posts:951
Registered: 6/7/01
Re: Question about reflection  
Jul 15, 2004 7:39 AM (reply 3 of 4)



 
If you're using jdk1.4+, you can create a new Throwable object and call getStackTrace().
 

Posts:951
Registered: 6/7/01
Re: Question about reflection  
Jul 15, 2004 8:01 AM (reply 4 of 4)



 
If you're using jdk1.4+, you can create a new Throwable object and call getStackTrace().

Doh! Didn't read salpeter's complete answer. Sorry.
 
This topic has 4 replies on 1 page.