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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With