java - 如何通过 Byte Buddy 为类中的公共(public)方法定义新注释

标签 java reflection annotations byte-buddy

我正在尝试使用 Byte Buddy 对类中使用自定义注释进行注释的所有公共(public)方法进行注释。

我已经尝试使用此处评论中的代码: Add method annotation at runtime with 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 注释的方法没有用Step 注释进行注释。 问题是什么? 或者我可能应该像教程中那样构建代理: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)));
    }
}

我还为代理定义了新类,但不太明白是否需要它,因为据我所知,它不适用于已加载的类,而我已经加载了一个。示例部分取自:Redefine java.lang classes with ByteBuddy 。尝试在此方法上添加断点,但应用程序并没有就此停止

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:类重定义失败:尝试更改架构(添加/删除字段)

最佳答案

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

相反,您需要通过在类加载器的 load 步骤中应用 ClassRedefinitionStrategy 来重新定义类。仅当您拥有可通过 ByteBuddyAgent 访问的可用 Instrumentation 实例时,这才有可能。

关于java - 如何通过 Byte Buddy 为类中的公共(public)方法定义新注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57578648/

相关文章:

java - 使用不同的服务器或机器将记录从一个数据库同步到另一个数据库

java - 使用 Java 反射调用变量方法?

javascript - 如何判断 JavaScript 函数是否已定义

java - 从 XDoclet 到注释的自动转换

string - 如何在 Matlab 中为文本添加轮廓?

Java:特定枚举和通用 Enum<?> 参数

java - 列表中的映射 - 如何使用 Stream 进行迭代

java - 什么将在 Java 中存储键值列表或在 Java 中存储 C# IDictionary 的替代品?

reflection - ThreeJS 中的镜像反射怪癖

python - 从 __future__ 导入注释