How use already transformed version of class in new tranformation by Byte-Buddy

47 Views Asked by At

Our project require programmatically specific logic and i wanted will write it via Byte-Buddy. So, me need know, how class can be transformed many times with save changes between iterations?

P.S. Multiple transforms me need because only in runtime can be possible know all specific-criterias and depending on it will be need some of transformations

Psedo-code:



public class Adapter {
    public void methodM1() {
        System.out.println("simple method m1 test");
    }
    public void methodM2() {
        System.out.println("simple method m2 test");
    }
}

public class InterceptorM1 {
    @RuntimeType
    public static Object intercept(@AllArguments Object[] allArguments) {
        System.out.println("method from swapping m1");
        return null;
    }
}

public class InterceptorM2 {
    @RuntimeType
    public static Object intercept(@AllArguments Object[] allArguments) {
        System.out.println("method from swapping m2");
        return null;
    }
}

public void example() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    Class<?> clazz = Adapter.class;

    new ByteBuddy()
            .subclass(Adapter.class)
            .method(named("methodM1"))
            .intercept(MethodDelegation.to(InterceptorM1.class))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    Class<?> dynamicType = new ByteBuddy()
            .subclass(Adapter.class)
            .method(named("methodM2"))
            .intercept(MethodDelegation.to(InterceptorM2.class))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    Adapter adapter = (Adapter) dynamicType.getDeclaredConstructor().newInstance();
    adapter.methodM1();
    adapter.methodM2();

}

Current result in console:

simple method m1 test
method from swapping m2

What i want get:

method from swapping m1
method from swapping m2

I found this examples, but I don’t have a complete understanding:

https://github.com/raphw/byte-buddy/blob/master/byte-buddy-dep/src/test/java/net/bytebuddy/ByteBuddyTutorialExamplesTest.java

0

There are 0 best solutions below