3

我正在尝试从类的实例中检索反射元数据。文档上的示例表明它应该是可能的,但我得到了undefined. 但是,如果我从类本身请求元数据,我会取回数据,与方法相同。

例如,这是完整的示例脚本:

import 'reflect-metadata'

const metadataKey = 'some-key'

@Reflect.metadata(metadataKey, 'hello class')
class C {
  @Reflect.metadata(metadataKey, 'hello method')
  get name(): string {
    return 'text'
  }
}

let obj = new C()
let classInstanceMetadata = Reflect.getMetadata(metadataKey, obj)
console.log(classInstanceMetadata) // undefined

let classMetadata = Reflect.getMetadata(metadataKey, C)
console.log(classMetadata) // hello class

let methodMetadata = Reflect.getMetadata(metadataKey, obj, 'name')
console.log(methodMetadata) // hello method

我的目标是取回一些数据classInstanceMetadata,让我将其与类类型相关联。

4

2 回答 2

4

发现我需要使用装饰器,然后在目标原型上定义元数据。

import 'reflect-metadata'

const metadataKey = 'some-key'

export const Decorate = (): ClassDecorator => {
  return (target: Function) => {
    @Reflect.metadata(metadataKey, 'hello class', target.prototype)
  }
}

@Decorate()
class C {
  get name(): string {
    return 'text'
  }
}
于 2018-11-13T16:14:51.743 回答
0

我想你可以省略()装饰器,这样@Decorate就足够了。此外,反射具有特定的元数据设计键,这取决于元数据/装饰器的使用:

  1. 类型元数据 ="design:type"
  2. 参数类型元数据 =>"design:paramtypes"
  3. 返回类型元数据 =>"design:returntype"
于 2019-12-12T12:10:27.450 回答