Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance of caller (via reflection) [duplicate]

is it somehow possible to get the instance object of the calling class?

class A{
    void foo(){
        Object o = getCaller(); //?? expect instance of B 
        long val1 = ..          // get val1 of o via reflection
        // do something where val1 is crucial
    }
}

class B{
    double val1 = Math.random();

    public static void main(String[] args) {
        new B().callFoo();
    }

    void callFoo(){
        new A().foo();
    }
}

I know that I can find out calling class/method via stacktrace but I need the conrete instance to access instance variables (like val1 in example).

I know it's dirty but class B is in an unchangable library so that it's nearly impossible to pass the required field without rebuilding everything.

like image 329
Marcel Avatar asked Oct 08 '15 15:10

Marcel


1 Answers

You can't access the instance of the caller unless the instance is somehow passed to it, or stored in a collection.

To pass the instance you can do the following :

class A{
    void foo(Object caller){
        long val1 = ..          
        // do something where val1 is crucial
    }
}

class B{
    double val1 = Math.random();

    public static void main(String[] args) {
        new B().callFoo();
    }

    void callFoo(){
        new A().foo(this);
    }
}

The "this" keywork will pass the instance of the calling code to the foo method in Class A

like image 151
Sandeep Salian Avatar answered Sep 27 '22 22:09

Sandeep Salian