简体   繁体   中英

Is there a way to retrieve the caller “object” in a Java agent using ByteBuddy?

To retrieve the class of the caller, we can use the StackWalker :

@Advice.OnMethodEnter
static void enter(@Advice.This Object thiz, 
                  @Advice.Origin Method method, 
                  @Advice.AllArguments Object... args) {
    var walker =  StackWalker.getInstance(RETAIN_CLASS_REFERENCE);
    var callerClass = walker.getCallerClass();
    ...
}

but is there a way to get a reference to the caller object, if it has not been garbage collected already?

In particular I am interested in the identity hash code of the caller object.

No, this is not possible, neither in a Java agent, nor without it. The only way to get the reference would be by instrumenting the caller of a method to provide its own instance reference.

Conceptually, I would however not recommend to go for this solution as it is very vulnerable to refactoring and would also yield undefined behavior if reflection, method handles or calls from static methods would occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM