A class representing
RuntimeVisibleAnnotations_attribute
and
RuntimeInvisibleAnnotations_attribute
.
To obtain an AnnotationAttribute object, invoke getAttribute(AnnotationsAttribute.visibleTag)
in ClassFile
, MethodInfo
, or FieldInfo
. The obtained attribute is a runtime visible annotations attribute. If the parameter is AnnotationAttribute.invisibleTag
, then the obtained attribute is a runtime invisible one.
For example,
import javassist.bytecode.annotation.Annotation; : CtMethod m = ... ; MethodInfo minfo = m.getMethodInfo(); AnnotationsAttribute attr = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.invisibleTag); Annotation an = attr.getAnnotation("Author"); String s = ((StringMemberValue)an.getMemberValue("name")).getValue(); System.out.println("@Author(name=" + s + ")");
This code snippet retrieves an annotation of the type Author
from the MethodInfo
object specified by minfo
. Then, it prints the value of name
in Author
.
If the annotation type Author
is annotated by a meta annotation:
@Retention(RetentionPolicy.RUNTIME)
Then Author
is visible at runtime. Therefore, the third statement of the code snippet above must be changed into:
AnnotationsAttribute attr = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag);
The attribute tag must be visibleTag
instead of invisibleTag
.
If the member value of an annotation is not specified, the default value is used as that member value. If so, getMemberValue()
in Annotation
returns null
since the default value is not included in the AnnotationsAttribute
. It is included in the AnnotationDefaultAttribute
of the method declared in the annotation type.
If you want to record a new AnnotationAttribute object, execute the following snippet:
ClassFile cf = ... ; ConstPool cp = cf.getConstPool(); AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag); Annotation a = new Annotation("Author", cp); a.addMemberValue("name", new StringMemberValue("Chiba", cp)); attr.setAnnotation(a); cf.addAttribute(attr); cf.setVersionToJava5();
The last statement is necessary if the class file was produced by Javassist or JDK 1.4. Otherwise, it is not necessary.
@see AnnotationDefaultAttribute
@see javassist.bytecode.annotation.Annotation