HarmonyOS ArkTS中如何判断某个类的实例是否实现了某个方法?

如题:HarmonyOS ArkTS中如何判断某个类的实例是否实现了某个方法?

阅读 539
1 个回答

示例参考如下:

function getMethods(classInstance: ESObject): string[] {
  return Object.getOwnPropertyNames(classInstance.prototype).filter(name =>
  typeof classInstance.prototype[name] === 'function' && name !== 'constructor');
}
class FuncObj {
  constructor() {
  }
  func0() {
    console.log('func0')
  }
  public func1() {
    console.log('func1');
  }
  private func2() {
    console.log('func2');
  }
  protected func3() {
    console.log('func3')
  }
}
@Entry
@Component
struct Index {
  @State funcNames: string = ''

  build() {
    Column() {
      Button('获取函数名称').onClick(() => {
        const methodList = getMethods(FuncObj) as string[]
        this.funcNames = methodList.join('、')
      }).margin({ bottom: 20 })
      Text(this.funcNames)
    }.justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .height('100%')
    .width('100%')
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏