HarmonyOS鸿蒙Next中自定义装饰器 自定义注解 反射

HarmonyOS鸿蒙Next中自定义装饰器 自定义注解 反射 反射:

import的方式实现反射功能: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkts-83-V5
ArkTs对应的Reflect阉割用法: https://developer.huawei.com/consumer/cn/blog/topic/03176991092068086
如何获取对象的所有方法: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkts-115-V5

可以使用TS三方库reflect-metadata获得类似java运行时注解的功能。参考 reflect-metadata

import "reflect-metadata"; 
 
// 三方包的能力暴露在Reflect中 
@Reflect.metadata("TargetClass", 'classData') 
 // 标记类,key是"TargetClass", 数据是classData 
class MyClass { 
  @Reflect.metadata("TargetMethod", 'methodData') 
 // 标记方法,key是"TargetMethod", 数据是methodData 
  myMethod() { 
  } 
 
  @Reflect.metadata("Static", 'staticData') 
  static invoke() { 
  } 
} 
 
// 运行时获取标记信息 
console.info(Reflect.getMetadata("TargetClass", MyClass)); //classData 
console.info(Reflect.getMetadata("TargetMethod", new MyClass(), "myMethod")); //methodData 
console.info(Reflect.getMetadata("Static", MyClass, "invoke")); // staticData

arkts自定义装饰器:

import { promptAction } from "@kit.ArkUI"

function MyDescriptor(target: Object, key: string, descriptor: PropertyDescriptor) {
  const originalMethod: Function = descriptor.value
  descriptor.value = (...args: Object[]) => {
    //类名: MyDescriptorCom 方法名: demoFunc  方法参数: DemoTest
    console.log(`类名: ${target.constructor.name} 方法名: ${key}  方法参数: ${args}`)
    //计算方法运行时间
    let start = Date.now().valueOf()
    const result: Object = originalMethod(...args)
    let time = Date.now().valueOf() - start
    promptAction.showToast({
      message: time/1000 + "秒",
      duration:5000
    })
    // 方法名 demoFunc 返回值: DemoTest
    console.log(`方法名 ${key} 返回值: ${result}`)
    return result
  }
  return descriptor
}

@Entry
@Component
export  struct MyDescriptorCom {
  @State message: string = 'Hello World';

  @MyDescriptor
  demoFunc(str:string) {
    for (let i = 0; i < 10000; i++) {
        str += i
    }
    return str
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
              this.demoFunc("12")
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中自定义装饰器 自定义注解 反射的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

更多关于HarmonyOS鸿蒙Next中自定义装饰器 自定义注解 反射的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,自定义装饰器和注解通过ArkTS的装饰器语法实现,使用@Component@Builder等装饰器扩展UI组件或方法。自定义注解通过@Decorator声明,用于标记类、方法或属性,支持元数据编程。反射功能受限,ArkTS提供部分反射API如Reflect.construct(),但出于安全考虑,系统限制了动态类型操作和运行时修改。开发者可通过预定义的装饰器和注解实现元编程需求,但需遵循静态类型和编译时检查机制。

在HarmonyOS Next中,自定义装饰器和反射功能主要通过ArkTS结合三方库实现。反射功能可以使用import方式导入reflect-metadata库,通过Reflect.metadataReflect.getMetadata实现类、方法级别的元数据标记与获取,支持运行时注解功能。自定义装饰器通过函数包装目标方法,修改其行为(如记录执行时间、日志输出等),适用于方法拦截和增强场景。需要注意的是,ArkTS的反射功能相对简化,部分高级特性需依赖三方库扩展。具体实现可参考官方文档提供的示例代码。

回到顶部