Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm learning asm, and I found two interesting api

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

and in 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);

But what's situation we will use this two method..

How can we generate an class with an annotation on a type in the class/method signature in java?

I try

 public @Z Integer testMethod(String testParam)

but @Z is still called by visitAnnotation not visitTypeAnnotation...

what's situation asm will call visitTypeAnnotation?

thx~

like image 485
robi Avatar asked Sep 02 '25 08:09

robi


1 Answers

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) but note that when the annotation supports the target METHOD at the same time, a declaration like

public @Z Integer testMethod(String testParam)

is ambiguos. Afaik, the annotation will be recorded for both, the method and the return type, then. Similarly, a declaration like

public Integer testMethod(@Z String testParam)

would be ambiguous if @Z supports the PARAMETER target at the same time.


Examples of unique uses where only type annotations can occur are

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

If you compare with the documentation of MethodVisitor.visitTypeAnnotation you may recognize the listed possible values for typeRef.

In case you are wondering how a METHOD_RECEIVER may get annotated, it’s a new Java 8 syntax that may not be commonly known:

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

In this example, the method receiver type of instanceMethod() is @Z Example rather than Example, though this difference has no meaning to the Java language itself.

like image 84
Holger Avatar answered Sep 05 '25 01:09

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!