You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取ElementAnnotation的起始偏移量与结束位置?

获取ElementAnnotation的位置偏移量

因为ElementAnnotation不属于Element类型,确实无法调用ParsedLibraryResult.getElementDeclaration。要获取它的起始/结束偏移量,核心是从它关联的**语法节点(AstNode)**入手,具体操作如下:

  • 直接访问ElementAnnotation的annotation属性,该属性返回Expression类型对象,而Expression是AstNode的子类。
  • 利用AstNode自带的offset属性获取注解的起始偏移量,end属性获取结束偏移量。

示例代码:

void getAnnotationOffsets(ElementAnnotation annotation) {
  if (annotation.annotation != null) {
    final AstNode annotationNode = annotation.annotation!;
    final int startOffset = annotationNode.offset;
    final int endOffset = annotationNode.end;
    // 可基于偏移量做后续源码定位、截取等操作
  }
}

注意事项:

  • 部分框架自动生成的隐式注解,可能存在annotation属性为null的情况,需提前做判空处理。
  • 若要验证偏移量对应的源码内容,可结合ParsedLibraryResult的content属性,通过偏移量截取对应源码片段确认。

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:34:55