ClassVisitor#visitTypeAnnotation 和 MethodVisitor#visitTypeAnnotation 的例子是什么

What's the example of ClassVisitor#visitTypeAnnotation and MethodVisitor#visitTypeAnnotation

我正在学习asm,我发现了两个有趣的东西api

org.objectweb.asm.ClassVisitor

/**
 * Visits an annotation on a type in the class signature.
 */
public AnnotationVisitor visitTypeAnnotation(int typeRef,
        TypePath typePath, String desc, boolean visible);

并在 org.objectweb.asm.MethodVisitor

/**
 * Visits an annotation on a type in the method signature.
 * 
 */
public AnnotationVisitor visitTypeAnnotation(int typeRef,
        TypePath typePath, String desc, boolean visible);

但是什么情况下我们会使用这两种方法..

我们如何在 java 中使用 an annotation on a type in the class/method signature 生成 class?

我试试

 public @Z Integer testMethod(String testParam)

但是 @Z 仍然被 visitAnnotation 调用而不是 visitTypeAnnotation...

asm 调用 visitTypeAnnotation 的情况是什么?

谢谢~

Type annotations are a new Java 8 feature. For enabling an annotation to be used in a type context, the annotation type must itself be annotated with @Target(ElementType.TYPE_USE) 但是注意当注解同时支持目标METHOD时,像

这样的声明
public @Z Integer testMethod(String testParam)

是歧义。 Afaik,然后将为方法和 return 类型记录注释。同样,像

这样的声明
public Integer testMethod(@Z String testParam)
如果 @Z 同时支持 PARAMETER 目标,

会产生歧义。


类型注释可以出现的独特用途示例是

public Integer testMethod(List<@Z String> testParam) throws @Z RuntimeException {
    return new @Z Integer(testParam.get((@Z int)0));
}

如果您与 documentation of MethodVisitor.visitTypeAnnotation 进行比较,您可能会认出 typeRef.

列出的可能值

如果您想知道 METHOD_RECEIVER 是如何被注释的,这是一个新的 Java 8 语法,可能不为人所知:

class Example {
    void instanceMethod(@Z Example this, int firstOrdinaryParameter) {
    }
}

在此示例中,instanceMethod() 的方法接收者类型是 @Z Example 而不是 Example,尽管这种差异对 Java 语言本身没有任何意义。