raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.23k stars 804 forks source link

include method does not exist for Method Delegation approach #1640

Closed arorakshayy closed 6 days ago

arorakshayy commented 4 months ago

I found this code online which tells bytebuddy where to search for the advice class: agentBuilder.transform( new AgentBuilder.Transformer.ForAdvice() .include( Utils.getBootstrapProxy(), Utils.getAgentClassLoader(), Utils.getExtensionsClassLoader()) .withExceptionHandler(ExceptionHandlers.defaultExceptionHandler()) .advice(methodMatcher, adviceClassName));

I verified and this works fine when working with advice. In my case, I am using MehtodDelegation and want the same functionality (similar method like 'include'). I want to explicitly tell bytebuddy where to look for intercepted classes. But, I couldn't find similar thing in MethodDelegation. Is there something that I am missing, or is there any other approach I can follow? I want to bypass the default class loading hierarchy and want byte buddy to search for classes in my custom class loaders.

raphw commented 4 months ago

MethodDelegation had different annotations. Are you sure that you placed the right one?

arorakshayy commented 4 months ago

MethodDelegation had different annotations. Are you sure that you placed the right one?

I tried multiple things. Nothing worked for me. My Delegated class is loaded by my custom loader and my agent could not load that when http call id made. Can you tell me exactly what will work here for MethodDelegation?

raphw commented 4 months ago

Well, there is two limitations:

arorakshayy commented 4 months ago

Well, there is two limitations:

  • The delegate class needs to be on the same class loader.

The delegate class needs to be on the same class loader. Is there any way to bypass this. I am instrumenting java http classes (loaded by bootstrap class loader). And my instrumentation classes are loaded by my custom class loader. Using Advice will have the overhead of causing issues at run time. Method delegation will prevent actual method implementation to conflict with my custom code.

raphw commented 4 months ago

No, that is how the JVM works, unfortunately. Advice, by default, inlines the code, this is why this is not the case here.

arorakshayy commented 4 months ago

Got it, one more thing While using advice, can I tell advice to not call the original method and return some custom mocked response? Is that possible? Is it a good approach?

raphw commented 6 days ago

Sorry, I missed that before. You can skip the original method using OnMethodEnter(skipOn = ...) and then set a different return value in OnMethodExit by using @Returned(readOnly = false) on a parameter.