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

时间:2017-10-12 09:59:29

标签: java byte-buddy

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.

1 个答案:

答案 0 :(得分:1)

您使用Advice作为拦截器而不是装饰器。这样,Byte Buddy实现了这个方法,默认情况下是一个超级方法调用,在你的情况下是不可能的。在创建子类时,这种模式主要是很快。您可以通过以下方式创建装饰:

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