gpt4 book ai didi

java - 使用 Byte Buddy 在运行时添加方法注释

转载 作者:行者123 更新时间:2023-11-30 12:04:07 25 4
gpt4 key购买 nike

几天来我一直在寻找“如何在运行时向方法添加注释”的答案,并找到了这个名为 Byte Buddy 的很棒的工具,使用了它,但仍然无法按我的需要使其工作到。我确定它必须能够从这个问题中做到这一点 Can Byte Buddy create fields and method annotations at runtime?

有这门课:

public class ClassThatNeedsToBeAnnotated {
public void method(int arg1, String arg2) {
// code that we don't want to touch at all, leave it as is
System.out.println("Called method with arguments " + arg1 + " " + arg2);
}

public void method() {
System.out.println("Called method without arguments");
}
}

和这段代码:

 public class MainClass {
public static void main(String[] args) {
ByteBuddyAgent.install();

AnnotationDescription description = AnnotationDescription.Builder.ofType(MyClassAnnotation.class)
.define("value", "new")
.build();

new ByteBuddy()
.redefine(ClassThatNeedsToBeAnnotated.class)
.annotateType(description)
.make()
.load(ClassThatNeedsToBeAnnotated.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

}
}

添加注解很容易。但是对于方法来说,不改变方法实现好像是不行的。

Method existingMethod = ClassThatNeedsToBeAnnotated.class.getDeclaredMethods()[0];
AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(MyMethodAnnotation.class)
.build();
new ByteBuddy()
.redefine(ClassThatNeedsToBeAnnotated.class)
.annotateType(description)
.method(ElementMatchers.anyOf(existingMethod))
// here I don't want to intercept method, I want to leave the method code untouched. How to do that?
.annotateMethod(annotationDescription)
.make()
.load(ClassThatNeedsToBeAnnotated.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

我确信我做的不对,但不幸的是找不到方法没有代码更改且只有注释更改的示例。

最佳答案

您在 Byte Buddy 中发现了一个盲点,我考虑了一段时间来解决这个问题。 Byte Buddy 的早期版本不允许定义注释,但当它允许时,API 已经被广泛使用,我无法更改它,而且它在实现中也需要一些位。

如果您愿意为添加合成方法付出最低的代价,您可以改为对类进行 rebase :

new ByteBuddy().rebase(ClassThatNeedsToBeAnnotated.class)

这样做,您可以只使用当前的 API 并添加 SuperMethodCall 的实现。这将在 rebase 中调用完全相同的方法。

此处跟踪了 Byte Buddy 的此增强功能:https://github.com/raphw/byte-buddy/issues/627

更新:在即将推出的 Byte Buddy 1.10.0 中,这可以通过以下方式实现:

new ByteBuddy()
.redefine(ClassThatNeedsToBeAnnotated.class)
.visit(new MemberAttributeExtension.ForMethod()
.annotateMethod(someAnnotation)
.on(matcher))
.make();

注解实例可以通过以下方式获取:AnnotationDescription.Latent.Builder.ofType(AnnotationClass.class).build()

关于java - 使用 Byte Buddy 在运行时添加方法注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com