HarmonyOS 获取class实例上的所有函数名

尝试了Object.getOwnPropertyNames()、Reflect.ownKeys(),这两个方式都是只能获取class上的static函数名,public、private、protected修饰的函数均无法获取,导致class实例上也获取不了函数名。for…in和prototype在ArkTs中又不支持。请问还有啥方式可以获取到吗?

HarmonyOS
2024-08-28 14:32:17
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

可以参考以下代码:

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%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.

ESObject主要用于在ArkTS和TS/JS跨语言调用的场景中作为类型标注,在非跨语言场景中使用ESObject标注类型,会引入不必要的跨语言调用,造成额外的性能开销,建议在非跨语言调用的场景下,避免使用ESObject,引入明确的类型进行注释。

文档说明:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faq-coding-V5#section1370411251371

分享
微博
QQ
微信
回复
2024-08-28 22:36:47
相关问题
ArkTSclass有析构函数吗?
1131浏览 • 1回复 待解决
Postgres:如何列出所有的聚合函数
3434浏览 • 2回复 待解决
如何获取Preferences实例
905浏览 • 1回复 待解决
首选项获取实例实例是否为单例
2648浏览 • 1回复 待解决
如何获取router push所有page?
1030浏览 • 0回复 待解决
如何获取对象所有方法
1333浏览 • 1回复 待解决
HarmonyOS 如何遍历获取page中所有view
491浏览 • 1回复 待解决
如何获取WindowStage实例主窗口?
1000浏览 • 1回复 待解决
HarmonyOS 获取本地所有音频文件
835浏览 • 1回复 待解决