Get an instance of the caller (not a class) of a method or constructor

Is it possible to get an instance of a caller of a method / constructor?

This question has already been posted, but every time the answers speak of the calling class (using stacktrace), and not the instance of the caller. If a solution exists, it can be very convenient to construct an object graph (with a common super-type) and handle parent child navigation using the default constructor.

public class TestCallStack { public static class BaseClass { BaseClass owner; // //ok, this is the correct way to do it // public BaseClass(BaseClass owner) { // this.owner = owner; // } public BaseClass() { //this.owner = ???????; } } public static class Parent extends BaseClass { Child child = new Child(); } public static class Child extends BaseClass { } public static void main(String[] args) { Parent parent = new Parent(); System.out.println(parent.child.owner==parent); // must be true } } 
+6
source share
1 answer

Your gut feeling is right - it's impossible. Personally, I think this is good, since it will make the code rather fragile with regard to refactoring (imagine that you are pulling some code into a static method - suddenly there is no calling object).

If you want to express any relationship with the owner, you must explicitly indicate this owner.

+7
source

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


All Articles