如何通过 Byte Buddy 在类中为公共方法定义新的注释



我正在尝试使用 Byte Buddy 注释我的类中的所有公共方法,这些方法都用我的自定义注释进行注释。

我已经尝试使用此处评论中的代码: 在运行时使用 Byte Buddy 添加方法注释

Java版本:1.8。 该应用程序用于测试微服务。 应用程序正在通过 Spring Boot 运行。 我尝试在我的应用程序中使用值注释来注释所有需要的方法,具体取决于方法名称。

<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.10.1</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.10.1</version>
</dependency>  

工作方法:


import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import io.qameta.allure.Step;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.MemberAttributeExtension;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.matcher.ElementMatchers;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
public class StackOverflowExample {
private static final String REGEX = "some-package";
public void configureAnnotation() {
Reflections reflections = getReflections();
Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
allClasses.forEach(clazz -> {
if (clazz.isAnnotationPresent(ConfigureSteps.class)) {
List<Method> publicMethods = Arrays.stream(clazz.getDeclaredMethods())
.filter(method -> Modifier.isPublic(method.getModifiers()))
.collect(Collectors.toList());
AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(Step.class)
                     .define("value", "new annotation")
                     .build();
publicMethods.forEach(method -> new ByteBuddy().redefine(clazz)
.visit(new MemberAttributeExtension.ForMethod()
        .annotateMethod(annotationDescription)
        .on(ElementMatchers.anyOf(method)))
.make());
}
});
}
private Reflections getReflections() {
return new Reflections(new ConfigurationBuilder().setScanners(new SubTypesScanner(false), new ResourcesScanner())
.addUrls(ClasspathHelper.forJavaClassPath())
.filterInputsBy(new FilterBuilder().include(REGEX)));
}
}

我在使用 JUnit @BeforeAll注释进行所有测试之前调用 configureAnnotation 方法。 调用方法没有问题,但我类中带有 ConfigureSteps 注释的方法没有使用步骤注释进行注释。 问题出在哪里? 或者也许我应该像这里的教程一样构建代理:http://bytebuddy.net/#/tutorial 在这种情况下,我应该以什么方式覆盖转换方法?

更新:在链中添加了加载方法;添加了

ByteBuddyAgent.install()
public class StackOverflowExample {
private static final String REGEX = "example-path";
public void configureAnnotation() {
Reflections reflections = getReflections();
Set<Class<?>> allClasses = reflections.getTypesAnnotatedWith(ConfigureSteps.class);
ByteBuddyAgent.install();
allClasses.forEach(clazz -> {
List<Method> publicMethods = Arrays.stream(clazz.getDeclaredMethods())
.filter(method -> Modifier.isPublic(method.getModifiers()))
.collect(Collectors.toList());
AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(Step.class)
                 .define("value", "new annotation")
                 .build();
publicMethods.forEach(method -> new ByteBuddy().redefine(clazz)
.visit(new MemberAttributeExtension.ForMethod()
    .annotateMethod(annotationDescription)
    .on(ElementMatchers.anyOf(method)))
.make()
.load(clazz.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent(
ClassReloadingStrategy.Strategy.REDEFINITION)));
});
}
private Reflections getReflections() {
return new Reflections(new ConfigurationBuilder().setScanners(new TypeAnnotationsScanner(), new SubTypesScanner(false), new ResourcesScanner())
.addUrls(ClasspathHelper.forJavaClassPath())
.filterInputsBy(new FilterBuilder().include(REGEX)));
}
}

此外,我为代理定义了新类,并不真正了解是否需要它,因为正如我所看到的,它不适用于加载的类并且我已经加载了一个。示例部分取自:使用 ByteBuddy 重新定义 java.lang 类。尝试在此方法上添加断点,但应用程序并未止步于此

import java.lang.instrument.Instrumentation;
import net.bytebuddy.agent.builder.AgentBuilder;
public class ExampleAgent {
public static void premain(String arguments,
Instrumentation instrumentation) {
new AgentBuilder.Default()
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
.with(AgentBuilder.InitializationStrategy.NoOp.INSTANCE)
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(instrumentation);
}
}

现在出现以下问题:java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)

通过调用make(),您将生成一个类文件并立即将其丢弃。

相反,您需要通过将load步骤中的ClassRedefinitionStrategy应用于类的类装入器来重新定义类。仅当您有可以通过ByteBuddyAgent访问的可用Instrumentation实例时,才有可能这样做。

最新更新