I'm sorry this question might be odd, but some time ago I used python's introspection, and I was wondering if something like that might be available in Java 1.8.
So let's say I have an object a
from class A
in a situation like this
class A{ B b; }
class B{ public void f(){} }
My question is "can f()
know about a
?"
Clearly, it can, if I add a backward link, something like:
class A {
B b;
public A() { b = new B(this); }
}
class B {
A father;
public B(A a){ this.father = a; }
public void f(){}
}
But my question is, in the general setting, without the back like to father
or so, is there any introspection mechanic that could allow f()
to know about a
?
You wish to access the arguments of a function upper in the call stack. In vanilla Java you can't accomplish that, however you can use some AOP framework, which could maintain a shadow stack, so you can introspect it.
Or you might use inner classes. Inner classes contain a hidden field to the instance of the outer class. It can be accessed with the syntax OuterClass.this
.
class A{
public class B{
public void f() {
System.out.println(A.this.aField);
}
}
String aField;
B b = new B(); // Passes a hidden `this` parameter
}