What class calls the method?

If there is a method in a class that could be called by any one of, lets say, one hundred other classes, in that method is there a way of printing out the name of the class that called it ?
So if class Xyz calls the method I would like to just do a println in the method saying that class Xyz called it ?

Yup... Thread.currentThread().getStackTrace();
package krc.utilz;
import java.io.PrintStream;
public class Tracer
  public static PrintStream out = null;
  public boolean enabled = true;
  public enum Format { LONG, SHORT }
  public Format format;
  public Tracer() {
    this(System.err, Tracer.Format.LONG);
  public Tracer(PrintStream out) {
    this(out, Tracer.Format.LONG);
  public Tracer(Format format) {
    this(System.err, format);
  public Tracer(PrintStream out, Format format) {
    this.out = out;
    this.format = format;
  public String toString() {
    return get(5);
  public String get() {
    return get(2);
  public String get(int i) {
    StackTraceElement[] st = Thread.currentThread().getStackTrace();
    if (i>=st.length) i = st.length-1; //don't go past top of stack
    StackTraceElement t = st;
String s = t.getFileName()+":"+t.getLineNumber()+":";
if (this.format == Format.LONG) {
s += t.getClassName()+"."+t.getMethodName();
return(s);
public void debug(String msg) {
if(!enabled)return;
out.println("DEBUG: "+msg);
public void print(String msg) {
if(!enabled)return;
if (out==null) return;
out.println(get(3)+" : "+msg);
public void print() {
if(!enabled)return;
if (out==null) return;
out.println(get(3));
public void print(int i) {
if(!enabled)return;
if (out==null) return;
out.println(get(i));
public static String getCurrentMethodName() {
StackTraceElement[] st = Thread.currentThread().getStackTrace();
return(st[2].getMethodName());

Similar Messages

  • What class called my method?

    I have tried using the StringWriter and the printStackTrace() methodology for finding out the name of the method that actually called my class and it works fine. But the problem is that the execution time is too high (abt 70msec). I need a better and more efficient way of finding this out.
    Does someone have an idea of how to do this?
    Regards,
    Manoj Rathod.

    Ok, this was my test code:
        public class MethodTrace {
            public static void main (String[] args) {
                method3(false);
            public static void method1 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method1: called by " + e[1].getMethodName());
                if (!stop) method3(false);
            public static void method2 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method2: called by " + e[1].getMethodName());
                if (!stop) method1(true);
            public static void method3 (boolean stop) {
                StackTraceElement e[] = (new Throwable()).getStackTrace();
                System.out.println("method3: called by " + e[1].getMethodName());
                if (!stop) method2(false);
        };And this was the output:
        method3: called by main
        method2: called by method3
        method1: called by method2As for the speed, I don't know. It's cleaner than using printStackTrace(), and I would think it would be faster. But I'm not sure.
    Why do you need to know the calling method, though? Perhaps there is some other, faster way to do what you want to do that doesn't have to use any stack tracing stuff at all.
    Or maybe you could just call the method, passing the name of the calling method as a String parameter:
        public void excellent (String caller) {
            System.out.println("Called by " + caller);
        public void superb () {
            excellent("superb");
        public void hard () {
            excellent("hard");
        };Lemme know if you find out anything interesting.
    Jason Cipriani
    [email protected]
    [email protected]

  • Which object called the method

    Suppose there is a class A which has three objects a1,a2,a3 and a method m. Now I'd like to know which particular object has called the method m.

    >
    which particular object has called the method
    What class called my method
    http://developer.java.sun.com/developer/qow/archive/104
    a.The advice in the posted link is unreliable as the format of printStackTrace() is not standardized. A more reliable way to find out the calling class is to use SecurityManager.getClassContext() or Throwable.getStackTrace() [in JDK 1.4+].
    However, it is not clear whether the original poster wanted to know the calling class or the calling object. In the latter case there is no easy way except for modify the signature of method m to accept the reference to the calling object.
    Vlad.

  • Call the method of a ejb??

    hi!
    I get EJB refrence ,How can I call the method of it?(I use the stand-alone application client)
    code:
    import javax.naming.*;
    //import javax.naming.InitialContext;
    import javax.rmi.*;
    import java.util.*;
    //import hello.*;
    public class jndi {
    public static void main(String[] args) {
    try {     
    Hashtable env = new Hashtable();
         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
    env.put(Context.PROVIDER_URL, "iiop://localhost:3000");
         Context initctx = new InitialContext(env);
         Object objref = initctx.lookup("HelloEJB");
    the method I want to call
    } catch (Exception ex) {
    System.err.println("Caught an unexpected exception!");
    ex.printStackTrace();
    Because it is the stand-alone .I can not to convert the objref:
    HelloHome helloHome =(HelloHome)objref;
    what can I do???

    It still can work.
    Tere is a ClassCastException.
    And the the class name of the objref is "com.sun.corba.se.internal.iiop.CDRInputStream_1_0$1".
    but my EJB is named HelloEJB.
    Is the object which I want to call????

  • Class call a method

    Hi,
    If you have numerous methods in a class, can you just call them like so:
    // in the .fla file
    var john:Person = new Person(63,150); // creates a new person named john 63" and 150lbs.
    john.weight(180); // changes johns weight to 180lbs.
    // in the .as file
    package {
        import flash.display.MovieClip;
        public class Person extends MovieClip {
            public var _perHeight:Number;
            public var _weight:Number;
          public function Person(perHeight:Number, weight:Number) {
                _perHeight=perHeight;
                _weight=weight;
                this.perHeight=_perHeight;
                this.weight=_weight;
            public function changeWeight(newWeight) {
                this.weight=newWeight;
    I must be calling the method completely wrong? I get this error:
    1061: Call to a possibly undefined method weight through a reference with static type Person.

    That is because the method is called "changeWeight" and you are using "weight."
    But what you really want is probably not a method but rather a getter/setter that acts like a property -- or maybe you just want a property.
    So in your class you would have this:
    package {
        import flash.display.MovieClip;
        public class Person extends MovieClip {
            private var _perHeight:Number;
            private var _weight:Number;
            private var _age:Number;
            public function Person(perHeight:Number, weight:Number) {
                _perHeight=perHeight;
                _weight=weight;
            public function set weight(num:Number):void{
                _weight=num;
           public function get weight():Number{
              return _weight;
    Then in your code (after creating a person instance):
    john.weight=180;// changes john's weight to 180.
    The cool thing about getters and setters is that they act just like a property when you use them, but they allow for a whole function call at the other end and can do various things based on the inputs.
    Also variable that start with an underscore are usually private variables. So in this case _weight, _age, and _perHeight would be private -- you couldn't access them directly through the john instance for example. And you would have appropriate getters and setters for them. For example you might make an age setter that didn't allow the number to be set as smaller than the current value or something.

  • To what class does this method belong?

    If one sees in the documentation something like
    - (retType *) text1:(Type1 *)aType1 text2:(Type2 *)aType2;
    then to what class does this method belong? I do not see in the Objective-C documentation any way that one can tell without the 'context' in which the method is declared or defined. This makes reading the documentation very difficult (for me). What you see is not what you get. There is stuff missing.
    In my world there is no difficulty in determining the class to which a method belongs. It is stated explicitly in the method name. For example:
    PROCEDURE (self: MyClass) methodName (arg1: Type1; arg2: Type2);
    and one sees that 'methodName' belongs to 'MyClass'.
    In Objective-C how does one know the class to which a method belongs? Is it only determined by context, that is, by the fact that it is within the @implementation section or that it is within the @interface section? If that is the case then I would think that in documentation one should always be required to assert something like:
    <<MyClass>> -(retType *) text1:(Type1 *)aType1 ...
    -Doug Danforth

    PeeJay2,
    I think I now have the distinctions needed but still have a question about what you said. But first here is my current understanding. A "method" is by definition bound to *at least* one class whereas a "message" need not be bound to any class. Hence one can send any message to any class and it will either be handled or ignored. A message looks like a method signature (and maybe one but is not constrained to be one).
    The difference between C++ and Objective-C is that in C++ method calls are not messages sent to a receiver. They are just calls of the method for the dynamically bound object. That method must be syntactically correct at compile time whereas messages need not be syntactically correct for any receiver. At least that is my current understanding.
    Now my question. You state that "casting the receiver of a message will in no way alter the flow of the code". I attempted to test this with a simple program but ran into a problem (see my new posting "Multiple classes in one file?").
    Assume the following
    @class Child : Parent
    Child *child = [[Child alloc] init];
    Parent *parent = [[Parent alloc] init];
    Parent *bar;
    bar = child;
    [bar doSomething]; // (C) call to child's doSomething method?
    [(Parent *)bar doSomething]; // (P) call to parent's doSomething method?
    You comment seems to say that both case (C) and (P) give the same result. If they do then which result is it the parent's or the child's method (assuming that the child has indeed reimplemented the parent's method)? Have I understood you correctly?
    -Doug Danforth

  • My Mac seems to be running slow, and what I call the rainbow wheel runs longer than I think it should.

    My Mac seems to be running slow, and what I call the rainbow wheel, runs much longer than I think it should.

    Step by Step to fix your Mac
    Why is my computer slow?
    Most commonly used backup methods
    If you get pinwheels when off the Internet, it coudl be a failing boot drive or just a few bad sectors as it has a hard time reading from it.
    This is a possible cure, it's a lot of work though.
    Reducing bad sectors effect on hard drives
    How to erase and install Snow Leopard 10.6

  • Telling which class called your method

    Does anybody know a way you can tell which class is calling your method? I mean:
    class A {
    public static void main(String args[]) {
    new A.doIt();
    void doIt() {
    B b = new B();
    b.callMe();
    class B {
    public void callMe() {
    String whoDidIt;
    whoDidIt=[stuff i'm asking for];
    System.out.println("I was called from an instance of class " + whoDidIt);
    How can I get that code to print "I was called from an instance of class A"???
    Lots of thanks in advance

    Pass the calling object to callMe as a parameter, egB b = new B();
    b.callMe(this);callMe becomes:
    public void callMe(Object caller)
       System.out.println("I was called from an instance of class " + caller.getClass());
    }Of course, there is nothing to stop anyone who calls the method passing a different object and confusing callMe.

  • There is something wrong with the volumes buttons in my macbook pro, every time i pressed the one who raises the volume, it leads me to the screen where (i do not no what its called) the background is black with the date and time and a calculator.

    There is something wrong with the volumes buttons in my macbook pro, every time i pressed the one who raises the volume, it leads me to the screen where (i do not no what its called) the background is black with the date and time and a calculator. However, when i lower it, my safari tab goes out of the screen. What do you guys think i should do? I'm getting very nervous.

    hey HAbrakian!
    You may want to try using the information in this article to adjust the behavior of your function keys to see if that resolves the behavior:
    Mac OS X: How to change the behavior of function keys
    http://support.apple.com/kb/ht3399
    Take care, and thanks for visiting the Apple Support Communities.
    -Braden

  • How can we call the method of used controller?

    Hi All,
       i created two WDA Applications.( like YWDA1,YWDA2 ) . i am using the component WDA2 in WDA 1.and displaying the one view of WDA2 as popup window in WDA1 on action of one of the input element in the view of WDA1 by using the method l_window_manager->create_window_for_cmp_usage
    I have a button on the view of WDA2 which has appear in the popup window...how can i call the method which has binded to that button....and where should i code that...and i need to assign selected value in the popup window to input elemetn of view  WDA1
    Please help me to resolve this....
    Regards,
    Ravi

    You can not directly call view's event handler from other component.
    create a method in component controller of the second component and in the button click call the component controller method. ( also make the method as interface so that you can call it from other components )
    Now, you can call the interfacecontroller's method
    DATA: l_ref_INTERFACECONTROLLER TYPE REF TO ZIWCI__VSTX_REBATE_REQ_WD .
      l_ref_INTERFACECONTROLLER =   wd_This->wd_CpIfc_<comp usage name>( ).
      l_ref_INTERFACECONTROLLER->Save_Rr(
        STATUS = '01'                       " Zvstxrrstatus
    save_rr is the method of second component controller

  • Display which method called the method (gives you a headache doesn't it)

    Hi,
    This question might sound a little weird, so maybe read it twice:
    I would like to see which method called the method.
    public void test1()
       test2();
    public void test2()
       System.out.println(....);
    The program output should be, test1 or classname.test1 or something like that. Is that possible?
    Thanx in advance, Yvo van Beek

    This should give you an idea:   public static void main (String args[]) {
          wereAreWe();
          caller2();
        public static void wereAreWe() {
          try {
            throw new RuntimeException("here we are");
          catch (Exception ex) {
            System.out.println("");       
            ex.printStackTrace(System.out);
        public static void caller1() {
          wereAreWe();
        public static void caller2() {
          caller1();
        }You can parse the result of printStackTrace() to get a more precise output.

  • Webdynpro error - what happened calling the webdynpropage was terminated ..

    Hello,
    in WD-Application rendering by portal browsing with Firefox clicking a button it appears a popup.
    The same WD-Application rendering by portal  browsing with IE 6.0 clicking a button it appears not popup but a browser error-message
    "webdynpro error - what happened calling the webdynpropage was terminated due to an error.
    Error type: sapPopupMainIdX1"
    Where is the probem.
    We use Portal Netweaver 2004s, SP11 and as backendystsem for WD for Abap Netweaver 2004s, SP 09.
    Best regards
    Oliver Prodinger

    The issue was actually caused by a kernel problem, as described in the topic
    SAP NetWeaver 2004s ABAP Trial Version SP8 Troubleshooting Guide
    I applied the recommended bug fixes and now it works perfectly!
    <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/6055f523-df6e-2910-f0bf-acccbb0a7d37">SAP NetWeaver 2004s ABAP Trial Version SP8 Troubleshooting Guide</a>
    Hope It will solve your problem
    Cheers
    Parag

  • How to call the method of a Business Object?

    Hi,
    Can someone guide me how to call the method of a business object?
    For example, I want to use the method SalesDocument.Copy of the Business Object VBAK. How can I do that? If you are familiar with any similar scenario please help.
    Regards,
    Renjith Michael.

    Hi
    double click on the copy  and
    go to abap tab
    there u can get functionmodule name
    u can call that
    Rewards if helpful

  • How to call the methods of JAR file into webDynpro Environment

    Hi All ,
             I have a requirement to call the methods of a JAR file into
             WebDynpro Environment. can anybody suggest me How this can be achieved. I Have a JAR file named FastTrack.API
    which contains few methods and i want these methods to be accessable into WebDynpro as other methods.
    Plz Somebody help me to sort this out.
    Regards,
    Deepak.

    Deepak,
    Please follow these 2 steps:
    1. Add jar into webdynpro project
            Right Click on ur project -> Select properties -> Java Buil path -> Choose Libraries Tab -> Add External Jars -> add the file from ur computer
    2. Use the jar
          write the import statement in your webdynpro code to utilize the properties of added jar.
    Thanks & Regards,
    Ram

  • Calling the method deployJava.installJRE("1.6*") always installs JRE7

    The call to deployJava.installJRE(verison, callback) in deployjava.js
    seems to ignore the version when we supply *"1.6*"* as a version and always installs the latest java 7.
    This happens if we had npdeployJava1.dll version 10.3.0.5 from Java7 still on the machine after uninstalling java7.
    Any ideas how to make it respect the version requested?
    note: deployjava.js is the deployment toolkit javascript that came before dtjava.js
    Edited by: bali on 05-Apr-2012 13:36
    Edited by: bali on 05-Apr-2012 13:37

    Only with The dt toolkit installed can deployJava install specific versions or families. The javascript will default, if no dt plugin is available to calling java.com to install the latest secure version available.
    After that, the dt plugin, deploy1ava1.dll, or npdeployJava1.dll should be available for IE and Firefox type browsers, and if not specifically disabled in the browser, you should be able to do this specif installation.
    My testing shows with JRE 8 or JRE 7, or some earlier JRE 6 version already installed, calling the method deployJava.installJRE("1.6*") currently installs 1.6.0_31.
    /Andy

Maybe you are looking for

  • Peculiar behavior of Shared Variable RT FIFO

    I'm trying to "leverage" the enhanced TCP/IP and Shared Variable properties of LabView 8.5.  My application involves (among other things) doing continuous sampling (16 channels, 1KHz/channel) using 6-year-old PXIs (Pentium III) and streaming data to

  • Skype video not working on Samsung TV

    I purchased the VG-STC2000 camera from the Skyp store for my Samsung series 6 smart tv. Video works on the tv screen and we can video chat between my laptop and the tv using our two different skype accounts. The issue is when we call, or receive a ca

  • How to track the mouseClick() on seperators between JTable TableHeader?

    Hi, Can anybody help me out telling how to track a mouseEvent on the JTable's TableHeader seperators, i.e. the seperators between the TableHeaders? Thanks in advance Logical_new_developer

  • Comparing field with select-option

    HI i have one slect option s_bukrs for coas-bukrs. and loop.. if w_bukrs eq s_bukrs"here is the problem,w_bukrs is    "holding single value and s_bukrs a range,so in such    "case how i can do comaprison endif. endloop

  • How do I save my preferences so I can totally remove FireFox

    Since I apparently cannot run Firefox until I eliminate everything, including my preferences, from my system, and since I really need Firefox, how do I save my preferences so I can restore them after I get Firefox running again?