mardi 28 mars 2017

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

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.





Aucun commentaire:

Enregistrer un commentaire