jeudi 8 octobre 2015

Get instance of caller (via reflection)

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.





Aucun commentaire:

Enregistrer un commentaire