英文:
Is visitAnnotation() always called before visitCode() in the ASM library?
问题
这是在visitAnnotation()
被调用的地方:
if (runtimeVisibleAnnotationsOffset != 0) {
attributeLength = this.readUnsignedShort(runtimeVisibleAnnotationsOffset);
for (currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; attributeLength-- > 0;
currentAnnotationOffset = this.readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, true), currentAnnotationOffset, true, charBuffer)) {
annotationDescriptor = this.readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
}
}
之后它调用了visitCode()
:
if (codeOffset != 0) {
methodVisitor.visitCode();
this.readCode(methodVisitor, context, codeOffset);
}
所以从这可以很明确地看出,visitAnnotation()
被首先调用,但这是否在某处有明确规定,或者仅仅是实现细节呢?
英文:
I'd like to instrument only methods annotated with @Test
, so before visitCode()
is called, I'd like to know if it's annotated with @Test
or not. From the tests I ran, I can say that visitAnnotation()
was always called first, but I don't know if this is always the case, or there are exceptions.
Update: code from ASM:
This is where visitAnnotation()
is called:
if (runtimeVisibleAnnotationsOffset != 0) {
attributeLength = this.readUnsignedShort(runtimeVisibleAnnotationsOffset);
for (currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; attributeLength-- > 0;
currentAnnotationOffset = this.readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, true), currentAnnotationOffset, true, charBuffer)) {
annotationDescriptor = this.readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
}
}
...
...
And after this, it calls visitCode()
:
if (codeOffset != 0) {
methodVisitor.visitCode();
this.readCode(methodVisitor, context, codeOffset);
}
So from this it is pretty clear, that visitAnnotation() is called first, but is this specified somewhere or is it just an implementation detail?
答案1
得分: 2
"ASM javadoc规定了所有方法调用的顺序,并且根据合同,此顺序是有保证的,visitAnnotation在visitCode之前被调用。如果您使用官方的ASM发射器,比如ClassReader,顺序将始终遵循规范。
然而,类型系统中没有内置的顺序保证。任何人都可以实现不同的顺序,而一些使用者,比如ClassWriter,可以容忍这种偏差,尽管这并不总是明确保证。
(由kriegaex更新)如果您想要确定,只需查看ASM手册第3.2.1章节,其中明确记录了这一点:"
英文:
The ASM javadoc specifes the order of all method calls and yes, by contract, this order is guaranteed, visitAnnotation is called before visitCode. If you use official ASM emitters such as ClassReader, the order will always follow the specification.
There is however no order guarantee built into the type system. Anybody could implement a different order and some consumers such as ClassWriter tolerate such deviation, even though it's not always explicitly guaranteed.
(Update by kriegaex) If you want to know for sure, just check out the ASM manual, chapter 3.2.1 where this is documented explicitly:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论