Can I get the instance of the calling object in Java?

不打扰是莪最后的温柔 提交于 2021-02-04 17:59:05

问题


There's a library which calls my method with a few arguments. I'd like to receive another argument, but the library doesn't provide it to the method it calls.

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

Is there a way I can get at the instance? SecurityManager has getClassContext(), but that just gives me the class of the instance - 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's b from here,
        // and A belongs to a library which I didn't write.
    }
}

Alternatively... I do know that b was used as an argument on the callstack. So if someone knows how I could access the b which was passed into A's constructor, that would be acceptable.

If neither of these are doable... I can decompile A and compile it the way I want, and then I'd either need to do some classloading wizardry or I'd have to modify the contents of the jar. Neither of those sound desirable, so I'm hopeful someone knows how to either access the instance of A or the argument b from the call stack.


回答1:


With the help of code you provided, i could think of writing an aspect i mean use aop and try using joinpoint to get the arguments that are passed to constructor A()




回答2:


Somehow I want to get at the calling instance of A's b from here

Short answer: you can't.

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

Yet another solution: use aspect-oriented programming with a framwork like AspectJ




回答3:


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

There is no such thing as an 'owner', so you cannot get the calling instance, unless an explicit reference to the parent is specified:

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 according to the library your are not supposed to get such instance, or it is poorly designed.



来源:https://stackoverflow.com/questions/43072542/can-i-get-the-instance-of-the-calling-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!