hotspot中的Java类对象如何保存注解
注解
Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。
Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。
注解的解析
类以及类中函数和字段的注解信息都是通过解析字节码文件获得。
// Sift through annotations, looking for those significant to the VM: static void parse_annotations(...) { ... const int atype = Bytes::get_Java_u2((address)abase + atype_off);//读取字节码 const int count = Bytes::get_Java_u2((address)abase + count_off); const Symbol* const aname = check_symbol_at(cp, atype); ... coll->set_annotation(... }注解的保存
关键是注解的保存。在hotspot中,使用Annotations类进行保存。
typedef Array<u1> AnnotationArray; class Annotations: public MetaspaceObj { ... AnnotationArray* _class_annotations; //类本身的注解集合 Array<AnnotationArray*>* _fields_annotations;//字段的注解集合 AnnotationArray* _class_type_annotations;//类type的注解集合 Array<AnnotationArray*>* _fields_type_annotations;//字段type的注解集合_class_annotations 和 _class_type_annotations的区别是
_class_annotations
@DeprecatedpublicclassMyClass{…} _class_type_annotations
@NonNullMyClass<String>obj;_fields_annotations 和 _fields_type_annotations的区别是
_fields_annotations
classExample{@Deprecatedintx;} _fields_type_annotations
classExample{List<@NonNullString>list;}在InstanceKlass中使用如下字段描述类中所有的注解
class InstanceKlass: public Klass { ... protected: ... Annotations* _annotations;