【问题标题】:Use ASM to add an annotation to a foreign class使用 ASM 给外部类添加注解
【发布时间】:2023-04-06 19:33:02
【问题描述】:

我想使用 ASM 字节码操作向外部类添加 Annotation,但我似乎遗漏了一些东西。打印出来的结果还是没有任何注释。

private void fixAnnotations4Classes() throws Exception {
        final ClassReader reader = new ClassReader("some/3rdparty/class/Foo");
        final ClassNode classNode = new ClassNode();
        reader.accept(classNode, 0);
        List<FieldNode> fields = classNode.fields;
        List<AnnotationNode> visibleAnnotations = fields.get(0).visibleAnnotations;
        visibleAnnotations.add(new AnnotationNode("my/new/Annotation"));

        ClassWriter writer = new ClassWriter(0);
        classNode.accept(writer);

        System.out.println(Arrays.toString(Foo.class.getDeclaredField("profile").getAnnotations()));
        System.out.println("FIN");
    }

【问题讨论】:

    标签: java bytecode-manipulation


    【解决方案1】:

    当您使用附加注释创建新类时,您永远不会替换实际加载的原始类文件。

    因此,您的 Foo 类将以其原始版本加载,或者它已经加载,因此您的更改是无效的。

    【讨论】:

    • 嗯,但我将如何“替换实际加载的原始类文件”?我认为这就是 ClassWriter 所做的。
    • 不,它只是生成一个代表修改后的类的字节数组。
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多