Search code examples
javamavenbyte-buddy

Modify library class at runtime - java/maven


I'm working on a Maven Plugin and I need to modify one class of an external jar (used during maven execution), to add:

  • a new field on this class
  • a getter for the field
  • some behavior to an existing setter to populate the field

The library code should use my 'new' class, and I want to be able to use the getter to retrieve some additional information.

Instances of this class are created within the library code (I'm not creating them in my code, I just need to access them). Class is a non-final public class.

Do you know if this feasible and which is the best way to do it? Is it possible to do it with ByteBuddy?

EDIT: I cannot wrap the class, because it's not instantiated in my own code, let me elaborate a bit.

There's a library class named "Parser" that instantiate and populate some "Element" instances. My code looks like:

List<library.Element> elements = new library.Parser(file).parse();

the Parser.parse() method calls "Element.setProperties(List properties)" on each element. I want to be able to enrich the setProperties method to store the original list of properties (that are lost otherwise)

Thanks Giulio


Solution

  • At the end I managed to obtain the wanted result with byte-buddy (I don't know if it's the best solution but it works):

    1. instrument library class (library.Element) using 'rebase' strategy to delegate the method 'setProperties' call to an interceptor.

    Note: this must be done as the first instruction of the maven plugin execution when library.Element.class is not yet loaded (I didn't want to use a JVM agent)

    1. define the above interceptor as a class that stores the original 'properties' value in a global map (key = identity hash code of the object, value = properties) and then call the original 'setProperties' method of library.Element

    2. change my code to get properties from the map, instead of library.Element getter (I had already a wrapper of this class).

    If someone is interested, I can show some code.