无法获取 class 实例的反映元数据
Cannot get reflect metadata of class instance
我正在尝试从 class 的实例中检索反射元数据。 docs 上的示例表明它应该是可能的,但我得到 undefined
。但是,如果我从 class 本身请求元数据,我会取回数据,与方法相同。
例如,这是完整的示例脚本:
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
中的一些数据,使我可以将其与 class 类型相关联。
发现我需要使用装饰器,然后在目标原型上定义元数据。
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'
}
}
我认为你可以在装饰器中省略 ()
,所以 @Decorate
就足够了。此外,reflect 具有 特定的元数据设计键 ,这取决于 metadata/decorator:
的使用
- 类型元数据 =
"design:type"
- 参数类型元数据=>
"design:paramtypes"
- Return 类型元数据 =>
"design:returntype"
我正在尝试从 class 的实例中检索反射元数据。 docs 上的示例表明它应该是可能的,但我得到 undefined
。但是,如果我从 class 本身请求元数据,我会取回数据,与方法相同。
例如,这是完整的示例脚本:
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
中的一些数据,使我可以将其与 class 类型相关联。
发现我需要使用装饰器,然后在目标原型上定义元数据。
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'
}
}
我认为你可以在装饰器中省略 ()
,所以 @Decorate
就足够了。此外,reflect 具有 特定的元数据设计键 ,这取决于 metadata/decorator:
- 类型元数据 =
"design:type"
- 参数类型元数据=>
"design:paramtypes"
- Return 类型元数据 =>
"design:returntype"