0

Javassist proxyFactory can create proxy at runtime with method interceptor. But how to add method interceptor to a class statically by modifying the class file?

For example, class Foo has 100 methods, before calling any method on an instance of Foo, need to check if the Foo instance is initialized.

public class Foo {

    public void methodA() {
        ...
    }

    public void methodB() {
        ...
    }

    public void methodC() {
        ...
    }

    ....
}

How to modify the class file to add such method interceptor? One way is to add code at the beginning of each method. Is there a better way?

How about other bytecode tools such as cglib, ....?

eastwater
  • 4,624
  • 9
  • 49
  • 118

1 Answers1

0

There are two options with ByteBuddy to achive this:

  • use redefine/rebase feature - You can check the details on ByteBuddy tutorial under 'type redefinition'/'type rebasing' tags. Limitation here is that this kind of transformation needs to be done before a target class is loaded.
  • Java Agent - agents run before class is loaded so they are allowed to modify existing classes. ByteBuddy comes with nice AgentBuilder (tutorial - 'Creating Java agents'). There is also posiblity to install special ByteBuddy agent at runtime (example from mentioned tutorial).

    class Foo {
      String m() { return "foo"; }
    }
    
    class Bar {
      String m() { return "bar"; }
    }
    
    ByteBuddyAgent.install();
    Foo foo = new Foo();
    new ByteBuddy()
      .redefine(Bar.class)
      .name(Foo.class.getName())
      .make()
      .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
    assertThat(foo.m(), is("bar"));
    
kaos
  • 1,598
  • 11
  • 15