我想拦截所有用@Inject 注释的方法。下面的测试表明它适用于方法,但不适用于构造函数。我错过了什么?
我尝试添加一个自定义方法匹配器,但我注意到我从未获得与构造函数对应的 MethodDescription。
public class InterceptConstructorTest {
@Test
public void testConstructorInterception() {
ByteBuddyAgent.install();
new AgentBuilder.Default().type(nameStartsWith("test")).transform(new AgentBuilder.Transformer() {
@Override
public Builder<?> transform(Builder<?> builder, TypeDescription td) {
return builder.method(isAnnotatedWith(Inject.class))
.intercept(MethodDelegation.to(MethodInterceptor.class).andThen(SuperMethodCall.INSTANCE));
}
}).installOnByteBuddyAgent();
// Call constructor => NOT intercepted
MyClass myClass = new MyClass("a param");
// Call method => intercepted
myClass.aMethod("a param");
}
}
class MyClass {
@Inject
public MyClass(String aParam) {
System.out.println("constructor called");
}
@Inject
public void aMethod(String aParam) {
System.out.println("aMethod called");
}
}
class MethodInterceptor {
public static void intercept(@Origin Method method) {
System.out.println("Intercepted: " + method.getName());
}
}
输出:
constructor called
Intercepted: aMethod
aMethod called