How to obtain a caller object reference from within a called method?
<p>I have to execute a given String as JavaScript code, e.g. <code>eval('Foo.setMessage("Hello!")')</code>, from within a class called <code>Engine</code>. Here, <code>setMessage()</code> is a public static method of the <code>Foo</code> class. Because I want to access some properties of the <code>Engine</code> object from within the <code>setMessage()</code> method, how can I obtain a reference to the <code>Engine</code> object?</p>

<p>I do know how to get the caller class name using <code>Reflection</code> or <code>CurrentThreadStack</code> or <code>Throwable</code> (see the code below), but these do not return a caller object reference.</p>

<p>//----------------------------------------------------------------  </p>

<p>@John: I have followed your four steps and made the following code. However, in the <code>Foo</code> class, I cann't get the right <code>Engine</code> object which is calling the <code>setMessage()</code> method. Thanks.</p>

<pre><code>import javax.script.*;

public class Engine {
    public static ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("ECMAScript");
    public String engineName;
    public String message;

    public Engine(String name) {
        this.engineName = name;
    }

    public void eval(String script) {
        try {
            Engine.scriptEngine.eval(script);
            //to do something more
        } catch (ScriptException e) {
            System.out.println(e.toString());
        }
    }

    public static void main(String[] args) {
        Engine firstEngine = new Engine("First engine");
        Engine.scriptEngine.put("firstEngine", firstEngine);
        firstEngine.eval("Packages.Foo.setMessage('Hello!');");

        Engine secondEngine = new Engine("Second engine");
        Engine.scriptEngine.put("secondEngine", secondEngine);
        secondEngine.eval("Packages.Foo.setMessage('Hello!');");
    }
}

public class Foo {
    public static void setMessage(String msg){
        Engine myEngine = (Engine)Engine.scriptEngine.get("What engine to get: first engine or second engine???");
        myEngine.message = msg;
        System.out.println(myEngine.engineName);
    }
}
</code></pre>

<p>Please help, thanks,
John</p>
