Get caller instance (via reflection)

Is it somehow possible to get an instance object of a 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 recognize a class / method call using stacktrace, but I need a conrete instance to access the instance variables (e.g. val1 in the example).

I know that it is dirty, but class B is in an immutable library, so it is almost impossible to pass the required field without rebuilding everything.

+5
source share
1 answer

You cannot access the instance of the caller unless the instance is somehow transferred to it or stored in the collection.

To transfer an 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 key "this" will pass the instance of the calling code to the foo method in class A

+2
source

Source: https://habr.com/ru/post/1233255/


All Articles