如何使用 ASM 读取 Java 类方法注释值

Tob*_*bse 4 java reflection annotations java-bytecode-asm modelmapper

如何在运行时使用ASM读取 Java 方法注释的值?
注释只有一个CLASS RetentionPolicy,因此不可能使用反射来做到这一点。

| 策略CLASS:注释将由编译器记录在类文件中,但不需要在运行时由VM保留

示例:我想在运行时从字段中
提取值:Carly Rae Jepsenartist

public class SampleClass {

    @MyAnnotation(artist = "Carly Rae Jepsen")
    public void callMeMaybe(){}
}
Run Code Online (Sandbox Code Playgroud)
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface MyAnnotation {

    String artist() default "";
}
Run Code Online (Sandbox Code Playgroud)

但为什么?
难道你不能只改变RetentionPolicytoRUNTIME并用反射来做吗?
简而言之:不。我使用modelmapper框架(简单、智能、对象映射)。在那里,我通过带注释的方法指定了 Java 类之间的双向映射。我不想重用此分层映射信息来进行更改事件传播。但提供的mapstruct org.mapstruct.Mapping注解有CLASS RetentionPolicy. 这就是为什么我需要从类文件中读取该信息 - 并且需要ASM

Tob*_*bse 5

有许多示例显示了 asm 的设置和阅读注释。但他们没有展示方法注释以及如何读取注释值。

\n\n

如何做到这一点的最小示例:

\n\n
import org.objectweb.asm.*;\n\npublic class AnnotationScanner extends ClassVisitor {\n    public static void main(String[] args) throws Exception {\n        ClassReader cr = new ClassReader(SampleClass.class.getCanonicalName());\n        cr.accept(new AnnotationScanner(), 0);\n    }\n\n    public AnnotationScanner() {\n        super(Opcodes.ASM8);\n    }\n\n    static class MyAnnotationVisitor extends AnnotationVisitor {\n        MyAnnotationVisitor() {\n            super(Opcodes.ASM8);\n        }\n        @Override\n        public void visit(String name, Object value) {\n            System.out.println("annotation: " + name + " = " + value);\n            super.visit(name, value);\n        }\n    }\n\n    static class MyMethodVisitor extends MethodVisitor {\n        MyMethodVisitor() {\n            super(Opcodes.ASM8);\n        }\n        @Override\n        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {\n            System.out.println("annotation type: " + desc);\n            return new MyAnnotationVisitor();\n        }\n    }\n\n    @Override\n    public MethodVisitor visitMethod(int access, String name, String desc,\n                                     String signature, String[] exceptions) {\n        System.out.println("method: name = " + name);\n        return new MyMethodVisitor();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

Maven依赖

\n\n
<dependency>\n  <groupId>org.ow2.asm</groupId>\n  <artifactId>asm</artifactId>\n  <version>8.0.1</version>\n</dependency>\n
Run Code Online (Sandbox Code Playgroud)\n\n

\xe2\x96\xb6它将打印:

\n\n
method: name = callMeMaybe\nannotation type: Lorg/springdot/sandbox/asm/simple/asm/MyAnnotation;\nannotation: artist = Carly Rae Jepsen\n
Run Code Online (Sandbox Code Playgroud)\n