在下面的代码片段中,我在 Subclass
的实例上调用一次 doStuff
方法。然而它被拦截了两次。
请注意,doStuff
是在父类 SuperClass
中定义的。如果在 SubClass
中定义了 doStuff
,则拦截逻辑将按预期工作:仅拦截一次。
我是否错误地使用了 Byte Buddy?
package com.test;
import static net.bytebuddy.matcher.ElementMatchers.any;
import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith;
import java.util.concurrent.Callable;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType.Builder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import org.junit.Test;
public class ReproBugTest {
@Test
public void reproBug() {
new AgentBuilder.Default().type(nameStartsWith("com.test"))
.transform(new AgentBuilder.Transformer() {
@Override
public Builder<?> transform(
Builder<?> builder,
TypeDescription td) {
return builder.method(any())
.intercept(
MethodDelegation.to(MethodInterceptor.class));
}
})
.installOn(
ByteBuddyAgent.installOnOpenJDK());
SubClass subClass = new SubClass();
subClass.doStuff();
}
}
class SuperClass {
public void doStuff() {
System.out.println("Doing stuff...");
}
}
class SubClass extends SuperClass {
}
class MethodInterceptor {
@RuntimeType
public static Object intercept(@SuperCall Callable<?> zuper)
throws Exception {
// Intercepted twice, bug?
System.out.println("Intercepted");
Object returnValue = zuper.call();
return returnValue;
}
}
最佳答案
您正在拦截每种类型的方法调用,即Subclass
和SuperClass
。您需要进一步指定您的拦截器拦截哪些方法。在您的情况下,您只想拦截由给定类型声明的方法。
这很容易实现。您应该拦截 builder.method(isDeclaredBy(td))
,而不是 builder.method(any())
。这样,只有由被拦截类型声明的方法才会被拦截。
最后,我可以从您的源代码中看到您使用的是旧版本的 Byte Buddy。版本 0.7-rc6 运行稳定,具有附加功能并修复了多个错误。 (但是,一些API仍然需要更改。)
关于java - 方法被拦截两次,即使它被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33464830/