Changing the behavior of a static method in Java byte manipulation

I am trying to manipulate a static method. You can use Byte Buddy or any other structure for this.

There is one library called Pi4J that is used to control GPIO from Raspberry Pi. This library has a method called:

GpioController gpio = GpioFactory.getInstance();

And this call is called in several places in the program, I may not have control, so I need to change the call.

What I would like to do is that when the GpioFactory.getInstancemethods are discovered and modified in some way GpioController, so they record that they were called.

Perhaps the only solution is to use AspectJ, but did you know if Byte Buddy could be the solution?

+2
source share
2 answers

Pi4J code is open source on github under the LGPL license. You can simply clone the repository, modify it and use your own version. If you feel that your changes can help others, also consider contributing to tp pi4j.

+2
source

This is possible when using the Java agent in combination with Byte Buddy . For example, you can change the method GpioFactory::getInstance, as shown in the following Java agent:

public class MyAgent {
  public static void premain(String arg, Instrumentation inst) {
    new AgentBuilder.Default()
      .type(ElementMatchers.named("com.pi4j.io.gpio.GpioFactory")
      .transform((builder, type) -> // Or anonymous class for pre Java 8
          builder.method(ElementMatchers.named("getInstance"))
                 .intercept(MethodDelegation.to(MyFactory.class));
      ).installOn(inst)
  }
}

public class MyFactory {
  public static GpioController intercept(@SuperCall Callable<GpioController> s) 
       throws Exception {
    return s.call(); // Wrap controller here.
  }
}

, , getInstance, MyFactory::intercept.

GpioController . .

Java- , JDK ( JVM), ByteBuddyAgent.install() ( byte-buddy-agent), . , GpioFactory. .

, , AspectJ Byte Buddy Java- . AspectJ , Byte Buddy API Java, .

+1

Source: https://habr.com/ru/post/1649024/


All Articles