Tom
Tom

Reputation: 71

Byte Buddy and ClassLoadingStrategy.UsingLookup

I've been using Byte Buddy within an OSGi application to implement a simple instrumentation service. One bundle provides an annotation that is used by client bundles to mark methods to be instrumented, and a method to be called from the client bundles' bundle activators. The call causes the client bundles' entries to be searched for classes with methods marked with the annotation. Each of those classes is read as byte code, augmented with Advice and preemptively loaded using the client bundles' class loaders.

I was using ClassLoadingStrategy.Default.INJECTION and ByteBuddy::redefine to load the classes. The need for the operation to be called from the client bundles' bundle activators is to get in before any of the original classes are loaded, thus avoiding the need for an agent.

I now notice the comment on INJECTION that says it will not work from Java 11 onward. I found the DZone article that presents ClassLoadingStrategy.UsingLookup as the new equivalent and shows how to ship code that should compile and run on Java 8 through 11.

  1. Can UsingLookup be used with redefine?
  2. Does the Lookup::defineClass not allow replacing classes that have already been loaded?
  3. Will I now have to make the client bundles include a 'hook' class in each of their packages that contain classes to be instrumented? The idea being that for each package the instrumenter can first load the hook class (using the client's class loader) then pass the Class in a call to MethodHandles::privateLookupIn to get a Lookup that can then be used to define and load the instrumented classes for that package.
  4. Do you have a better idea than 3?

Thanks!

Upvotes: 1

Views: 469

Answers (1)

Tom
Tom

Reputation: 71

I found that placing a package-info.java in each of the target packages and loading that 'class' provided a neat-ish hook. However, I then learned of OSGi Weaving Hooks and used that instead.

Upvotes: 1

Related Questions