可以使用TS三方库reflect-metadata获得类似java运行时注解的功能。
reflect-metadata提供的装饰器允许对类和类属性和类方法做标记,并提供了接口可以在运行时获取标记的信息。
import "reflect-metadata";
// 三方包的能力暴露在Reflect中
@Reflect.metadata("TargetClass", 'classData')
// 标记类,key是"TargetClass", 数据是classData
class MyClass {
@Reflect.metadata("TargetMethod", 'methodData')
// 标记方法,key是"TargetMethod", 数据是methodData
myMethod() {
}
@Reflect.metadata("Static", 'staticData')
static invoke() {
}
}
// 运行时获取标记信息
console.info(Reflect.getMetadata("TargetClass", MyClass)); //classData
console.info(Reflect.getMetadata("TargetMethod", new MyClass(), "myMethod")); //methodData
console.info(Reflect.getMetadata("Static", MyClass, "invoke")); // staticData