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

问题描述

您在Byte Buddy中发现了一个盲点,我想修复一会儿。早期版本的Byte Buddy不允许定义注释,但是当它允许时,该API已经被广泛使用,以至于我无法更改它,并且在实现中也需要一些位。

如果您愿意为添加合成方法付出最小的代价,则可以改类为基础:

new ByteBuddy().rebase(ClassThatNeedsToBeAnnotated.class)

这样做,您可以仅使用当前的API并添加的实现SuperMethodCall。这将在重新基准化中调用完全相同的方法

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

:在即将发布的字节好友1.10.0中,可以通过以下方式实现:

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

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

解决方法

我一直在寻找“如何在运行时向方法添加注释”的答案,发现了一个名为Byte
Buddy的出色工具,可以使用它,但仍然无法按需使用。我确定它必须能够从这个问题做到这一点Byte
Buddy可以在运行时创建字段和方法注释吗?

上这堂课:

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());

我敢肯定,我只是做得不好,但是不幸的是,当方法 没有代码更改 而只有注释更改时,找不到示例。

猜你在找的技术问答相关文章

如何检查配对的蓝牙设备是打印机还是扫描仪(Android)
是否允许实体正文进行HTTP DELETE请求?
如何将ZipInputStream转换为InputStream?
java.util.logging Java 8中的变量
PowerMockito.doReturn返回null
Java中的RESTful调用
Swing / Java:如何正确使用getText和setText字符串
特殊字符和重音字符
Android Studio中的ndk.dir错误
错误“找不到主类”