【far 语言】注解系统

本文是「far 语言」系列文档之一,总目录见《【far 语言】语言文档目录》。

注解系统

Far 注解为 Java 风格:@名字@名字(参数...),注解名首字母必须大写。

使用注解

@Extern("c", "strlen")                 // 内建注解:FFI 声明外部 C 函数
static long strlen(RawPtr<AbiChar> s);

@Retention(RUNTIME)                    // 保留策略:运行期保留
@Component                              // 自定义注解
class OrderController { ... }

保留策略

级别 语义
SOURCE(默认) 编译期消费,编译后彻底消失(如 @Extern
RUNTIME @Retention(RUNTIME) 标记 → 编译期生成元数据表 → 运行期反射读取

自定义注解(仿 Java @interface)

@Retention(RUNTIME)                 // 保留策略(应用到注解类型声明)
@Target(CLASS, METHOD, FIELD)       // 目标限定(默认全部允许)
annotation MyAnno {
    string name;                    // 无默认值 = 必填参数
    string path = "";               // 有默认值 = 可选参数
}
  • 关键字 annotation,注解类型名首字母必须大写。
  • 参数类型限 string / long / bool
  • @Retention / @Target 仅允许出现在注解类型声明前。
  • @Target 目标:CLASS / METHOD / FIELD
  • 注解参数值:字符串/数字/标识符,或编译期纯内置函数调用str/toString/toLong/toInt/toDouble/len/size/substr,参数可嵌套,2026-08-23):
  • @Tag(name = str(42), msg = substr("hello", 0, 3)) → 编译期求值为 "42" / "hel"
  • 不支持运算符表达式与非纯函数(注解参数必须编译期常量)

使用自定义注解

@Retention(RUNTIME)
@Target(CLASS)
annotation Component {
    string name = "";
}

@Component
class App { ... }
  • 未声明的注解名 → 编译报错。
  • 目标不匹配(如 @Target(FIELD) 标在方法上)→ 编译报错。
  • 必填参数缺失 / 参数名不存在 / 值类型不匹配 → 编译报错。

运行期反射 API

// 顶层函数(需 @Retention(RUNTIME) 才可读)
hasAnnotation(类名, 方法名, 注解名)          → bool(方法名空串 = 类级)
getAnnotation(类名, 方法名, 注解名)          → string(参数编码串)
annotationArg(类名, 方法名, 注解名, key)     → string
annotationsOf(类名, 方法名)                  → string[](注解名列表)
annotationMap(类名, 方法名, 注解名)          → map<string,string>(参数名→值)
posted @ 2026-09-13 05:05  方东信  阅读(4)  评论(0)    收藏  举报