背景:我想使用 LogInterceptor 来检测一组接口(interface)(在同一包内)的所有实现(仅记录调用该方法的情况)。因此我用byte-buddy写了一个javaagent。一般来说,这工作正常,但我正在努力寻找一组接口(interface)的所有实现。
假设我们在 my.company.api 包中有一组 Java 接口(interface),那么我尝试了以下方法:
public static void premain(String arguments, Instrumentation instrumentation) {
new AgentBuilder.Default()
.ignore(ElementMatchers.isInterface())
.ignore(ElementMatchers.isEnum())
.type(ElementMatchers.nameMatches("my\\.company\\.api\\..*"))
.transform(new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder transform(DynamicType.Builder builder, TypeDescription typeDescription, ClassLoader classloader) {
return builder
.method(ElementMatchers.isPublic())
.intercept(MethodDelegation.to(LogInterceptor.class));
}
}).installOn(instrumentation);
}
我对 byte-buddy 很陌生,也许有人可以给我提示我做错了什么。
最佳答案
首先,您没有正确链接忽略匹配器;应该是:
.ignore(isInterface().or(isEnum()))
对于接口(interface)的匹配,你可以尝试使用hasSuperType
匹配器。如果您尝试匹配给定包的接口(interface),您可以尝试:
hasSuperType(nameStartsWith("my.company.api.").and(isInterface()))
与正则表达式相比,使用前缀匹配器效率更高。
关于java - 使用 ByteBuddy 检测一组接口(interface)的所有实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917619/