Can I get an instance of the caller in Java?

There is a library that calls my method with several arguments. I would like to get another argument, but the library does not provide it to the method that it calls.

By decompiling the library, I see that it has an argument and is assigned to the instance variable (not private, but not public). I know that I can get a variable using reflection if I have an instance, but I don't have an instance either.

Is there any way to get an instance? SecurityManager has getClassContext () , but it just gives me an instance class - I want the instance itself.

As a quick example of what I want:

public class A { int b; public A(int b, int c) { this.b = b; D(c); } } public class D { public D(int c) { // Somehow I want to get at the calling instance of A b from here, // and A belongs to a library which I didn't write. } } 

Alternatively ... I know that b used as an argument in callstack. Therefore, if someone knows how I could access b , which was passed to constructor A , that would be acceptable.

If none of them is feasible ... I can decompile A and compile it the way I want, and then I will either need to do some skill in loading classes, or I will have to modify the contents of the jar, None of these sounds is not desirable, so I hope someone knows how to access instance A or argument b from the call stack.

+5
source share
3 answers

With the code you provided, I could think of writing an aspect that I mean by using aop and trying to use a join point to get the arguments that are passed to the A () constructor

+2
source

Somehow I want to get from the calling instance A b from here

Short answer: you cannot.

Long answer: you can get it if you either run it on the debugger or your own JVM.

Another solution: use aspect-oriented programming with a framework like AspectJ

+1
source

You cannot do this. See this post for more details.

There is no such thing as an β€œowner”, so you cannot get the calling instance unless you explicitly reference the parent:

 class A { int b; A(int b, int c) { this.b = b; new D(this, c); } } class D { D(A a, int c) { ... } } 

It seems that either in accordance with the library you should not receive such an instance, or it is poorly designed.

0
source

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


All Articles