简体   繁体   中英

Redefine class, intercepting getter method in order to modify the getter return value

I defined my Advice in this way:

public class MyInterceptor {
    @Advice.OnMethodExit
    public static void intercept(@Advice.Return String value) {
        // do my changes
    }
}

This is my class to be redefined:

public class MyClass {

    private String field;

    public MyClass() {
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }
}

My JUnit Test:

@Test
public void buddytest() throws Exception {

    new ByteBuddy()
        .redefine(MyClass.class)
        .method(named("getField"))
        .intercept(to(MyInterceptor.class))
        .make()
        .load(getClass().getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

    MyClass myClass = new MyClass();
    myClass.setField("xxx");
    String field = myClass.getField();
}

But when I run my test, MyInterceptor.intercept() method is not called and this Exception is thrown:

java.lang.IllegalStateException: Cannot call super (or default) method for public java.lang.String package.MyClass.getField()

What am I doing wrong? Thank you in advance.

You are using Advice as an interceptor and not like a decorator. This way, Byte Buddy implements the method, by default as a super method call what is not possible in your case. This pattern makes mostly sence when creating subclasses. You can create a decoration by:

new ByteBuddy()
    .redefine(MyClass.class)
    .visit(Advice.to(MyInterceptor.class).on(named("getField")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM