ts 如何获取一个类的所有公有方法
在 TypeScript 中,可以通过反射机制获取一个类的所有公有方法。具体步骤如下:
- 导入 reflect-metadata 库。
import "reflect-metadata";
- 使用 Reflect.getMetadataKeys() 方法获取该类的元数据键。
const metadataKeys = Reflect.getMetadataKeys(MyClass.prototype);
- 遍历元数据键,使用 Reflect.getMetadata() 方法获取每个键对应的元数据。
const methods = [];
for (const key of metadataKeys) {
const metadata = Reflect.getMetadata(key, MyClass.prototype);
if (typeof metadata.value === "function") {
methods.push(metadata.key);
}
}
- 最终得到的 methods 数组即为该类所有公有方法的名称数组。
完整代码示例:
import "reflect-metadata";
class MyClass {
public foo() {}
private bar() {}
}
const metadataKeys = Reflect.getMetadataKeys(MyClass.prototype);
const methods = [];
for (const key of metadataKeys) {
const metadata = Reflect.getMetadata(key, MyClass.prototype);
if (typeof metadata.value === "function") {
methods.push(metadata.key);
}
}
console.log(methods); // ["foo"]
``
原文地址: http://www.cveoy.top/t/topic/hxHw 著作权归作者所有。请勿转载和采集!