【问题标题】:What's the example of ClassVisitor#visitTypeAnnotation and MethodVisitor#visitTypeAnnotationClassVisitor#visitTypeAnnotation 和 MethodVisitor#visitTypeAnnotation 的例子是什么
【发布时间】:2015-04-15 09:21:03
【问题描述】:

我在学习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 的类?

我试试

 public @Z Integer testMethod(String testParam)

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

什么情况下asm会调用visitTypeAnnotation?

谢谢~

【问题讨论】:

  • Z@Target(ElementType.TYPE_USE) 注释吗?
  • @immibis 哦~~~,谢谢 immibis,我明白了.. Type Annotation 是 Java 8 的新功能,我学习了一些 Type Annotation 信息并升级到 Java 8,标记 @987654332 @ to @Z 它可以工作......谢谢你~(我仍然使用jdk7)

标签: java java-8 java-bytecode-asm


【解决方案1】:

Type annotations 是 Java 8 的一项新功能。为了使注解能够在类型上下文中使用,注解类型本身必须使用 @Target(ElementType.TYPE_USE) 进行注解,但请注意,当注解同时支持目标 METHOD 时,声明如

public @Z Integer testMethod(String testParam)

是模棱两可的。 Afaik,然后将为方法和返回类型记录注释。类似地,像

这样的声明
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 语言本身没有任何意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多