鸿蒙NEXT开发对象工具类(TS)

复制代码
import util from '@ohos.util';
import { ArrayList, HashMap, JSON, List } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// 定义通用单个联合类型
export type CommonSingleType = Object | string | number | boolean | null | undefined;

// 定义通用所有联合类型
export type CommonAllType =
  | CommonSingleType
    | Array<CommonSingleType>
    | ArrayList<CommonSingleType>
    | HashMap<CommonSingleType, CommonSingleType>;

// 定义构造函数类型
export type Constructor<T> = new (...args: any[]) => T;

/**
 * 对象工具类
 */
export class ObjectUtil {
  /**
   * 获取对象的Hash值。如果是第一次获取,则计算Hash值并保存到对象的Hash域(返回随机的Hash值);如果不是第一次获取,则从Hash域中获取并返回Hash值(同一对象多次返回值保持不变)。
   * @param object - 目标对象
   * @returns Hash值
   */
  static getHash(object: Object): number {
    return util.getHash(object);
  }

  /**
   * 获取对象的Class名称
   * @param obj - 目标对象
   * @returns Class名称
   */
  static getClassName(obj: Object): string {
    return obj.constructor.name;
  }

  /**
   * 获取对象的所有方法名
   * @param obj - 目标对象
   * @returns 方法名数组
   */
  static getMethodsNames(obj: Object): string[] {
    const prototype = Object.getPrototypeOf(obj);
    return Object.getOwnPropertyNames(prototype).filter(
      (key) => typeof Reflect.get(prototype, key) === 'function' && key !== 'constructor'
    );
  }

  /**
   * 判断是否是String
   * @param source - 输入值
   * @returns 是否为字符串
   */
  static isString(source: unknown): boolean {
    return typeof source === 'string' || source instanceof String;
  }

  /**
   * 判断对象是否为空
   * @param source - 输入值
   * @returns 是否为空
   */
  static isNull(source: CommonAllType): boolean {
    return source === null || source === undefined;
  }

  /**
   * 判断属性内容是否为空
   * @param property - 输入值
   * @returns 是否为空
   */
  static isEmpty(property: CommonAllType): boolean {
    if (this.isNull(property)) {
      return true;
    }
    if (Array.isArray(property) || property instanceof ArrayList) {
      return property.length === 0;
    }
    if (property instanceof HashMap) {
      return property.isEmpty();
    }
    return property === '';
  }

  /**
   * 浅拷贝
   * @param obj - 被拷贝对象
   * @returns 拷贝后的对象
   */
  static shallowCopy<T extends Record<string, any>>(obj: T): T {
    return { ...obj };
  }

  /**
   * 深度拷贝
   * @param obj - 被拷贝对象
   * @returns 深拷贝后的对象
   */
  static deepCopy<T>(obj: T): T {
    if (typeof obj !== 'object' || obj === null) {
      return obj; // 非对象或null直接返回
    }

    if (Array.isArray(obj)) {
      return obj.map((item) => this.deepCopy(item)) as unknown as T;
    }

    const newObj: Record<string, any> = {};
    for (const key in obj) {
      if (Reflect.has(obj, key)) {
        newObj[key] = this.deepCopy(Reflect.get(obj, key));
      }
    }
    return newObj as T;
  }

  /**
   * 合并两个或多个对象
   * @param target - 目标对象
   * @param sources - 源对象数组
   * @returns 合并后的对象
   */
  static assign(target: Record<string, any>, ...sources: Record<string, any>[]): Record<string, any> {
    for (const source of sources) {
      for (const key of Object.keys(source)) {
        target[key] = Reflect.get(source, key);
      }
    }
    return target;
  }

  /**
   * 将普通对象转换为类实例
   * @param clazz - 类构造函数
   * @param obj - 普通对象
   * @returns 类实例
   */
  static objToClass<T>(clazz: Constructor<T>, obj: Record<string, any>): T {
    const instance = new clazz();
    return Object.assign(instance, obj);
  }

  /**
   * 删除Record中的元素
   * @param record - Record对象
   * @param key - 键
   */
  static deleteRecord(record: Record<string, any>, key: string): void {
    Reflect.deleteProperty(record, key);
  }

  /**
   * 通过key获取对象值
   * @param obj - 目标对象
   * @param key - 键
   * @returns 值
   */
  static getValue<T = unknown>(obj: Record<string, any>, key: string): T {
    return Reflect.get(obj, key) as T;
  }

  /**
   * 给对象动态添加或修改属性
   * @param obj - 目标对象
   * @param key - 键
   * @param value - 值
   */
  static setValue<T>(obj: Record<string, any>, key: string, value: T): void {
    Reflect.set(obj, key, value);
  }

  /**
   * 获取Error的JSON字符串
   * @param error - 错误对象
   * @returns JSON字符串
   */
  static getErrorStr(error: BusinessError): string {
    const errObj: Record<string, string | number> = {
      name: error.name,
      code: error.code,
      message: error.message,
      stack: error.stack ?? '',
    };
    return JSON.stringify(errObj);
  }
}

代码如下:

TypeScript 复制代码
import util from '@ohos.util';
import { ArrayList, HashMap, JSON, List } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

// 定义通用单个联合类型
export type CommonSingleType = Object | string | number | boolean | null | undefined;

// 定义通用所有联合类型
export type CommonAllType =
  | CommonSingleType
    | Array<CommonSingleType>
    | ArrayList<CommonSingleType>
    | HashMap<CommonSingleType, CommonSingleType>;

// 定义构造函数类型
export type Constructor<T> = new (...args: any[]) => T;

/**
 * 对象工具类
 */
export class ObjectUtil {
  /**
   * 获取对象的Hash值。如果是第一次获取,则计算Hash值并保存到对象的Hash域(返回随机的Hash值);如果不是第一次获取,则从Hash域中获取并返回Hash值(同一对象多次返回值保持不变)。
   * @param object - 目标对象
   * @returns Hash值
   */
  static getHash(object: Object): number {
    return util.getHash(object);
  }

  /**
   * 获取对象的Class名称
   * @param obj - 目标对象
   * @returns Class名称
   */
  static getClassName(obj: Object): string {
    return obj.constructor.name;
  }

  /**
   * 获取对象的所有方法名
   * @param obj - 目标对象
   * @returns 方法名数组
   */
  static getMethodsNames(obj: Object): string[] {
    const prototype = Object.getPrototypeOf(obj);
    return Object.getOwnPropertyNames(prototype).filter(
      (key) => typeof Reflect.get(prototype, key) === 'function' && key !== 'constructor'
    );
  }

  /**
   * 判断是否是String
   * @param source - 输入值
   * @returns 是否为字符串
   */
  static isString(source: unknown): boolean {
    return typeof source === 'string' || source instanceof String;
  }

  /**
   * 判断对象是否为空
   * @param source - 输入值
   * @returns 是否为空
   */
  static isNull(source: CommonAllType): boolean {
    return source === null || source === undefined;
  }

  /**
   * 判断属性内容是否为空
   * @param property - 输入值
   * @returns 是否为空
   */
  static isEmpty(property: CommonAllType): boolean {
    if (this.isNull(property)) {
      return true;
    }
    if (Array.isArray(property) || property instanceof ArrayList) {
      return property.length === 0;
    }
    if (property instanceof HashMap) {
      return property.isEmpty();
    }
    return property === '';
  }

  /**
   * 浅拷贝
   * @param obj - 被拷贝对象
   * @returns 拷贝后的对象
   */
  static shallowCopy<T extends Record<string, any>>(obj: T): T {
    return { ...obj };
  }

  /**
   * 深度拷贝
   * @param obj - 被拷贝对象
   * @returns 深拷贝后的对象
   */
  static deepCopy<T>(obj: T): T {
    if (typeof obj !== 'object' || obj === null) {
      return obj; // 非对象或null直接返回
    }

    if (Array.isArray(obj)) {
      return obj.map((item) => this.deepCopy(item)) as unknown as T;
    }

    const newObj: Record<string, any> = {};
    for (const key in obj) {
      if (Reflect.has(obj, key)) {
        newObj[key] = this.deepCopy(Reflect.get(obj, key));
      }
    }
    return newObj as T;
  }

  /**
   * 合并两个或多个对象
   * @param target - 目标对象
   * @param sources - 源对象数组
   * @returns 合并后的对象
   */
  static assign(target: Record<string, any>, ...sources: Record<string, any>[]): Record<string, any> {
    for (const source of sources) {
      for (const key of Object.keys(source)) {
        target[key] = Reflect.get(source, key);
      }
    }
    return target;
  }

  /**
   * 将普通对象转换为类实例
   * @param clazz - 类构造函数
   * @param obj - 普通对象
   * @returns 类实例
   */
  static objToClass<T>(clazz: Constructor<T>, obj: Record<string, any>): T {
    const instance = new clazz();
    return Object.assign(instance, obj);
  }

  /**
   * 删除Record中的元素
   * @param record - Record对象
   * @param key - 键
   */
  static deleteRecord(record: Record<string, any>, key: string): void {
    Reflect.deleteProperty(record, key);
  }

  /**
   * 通过key获取对象值
   * @param obj - 目标对象
   * @param key - 键
   * @returns 值
   */
  static getValue<T = unknown>(obj: Record<string, any>, key: string): T {
    return Reflect.get(obj, key) as T;
  }

  /**
   * 给对象动态添加或修改属性
   * @param obj - 目标对象
   * @param key - 键
   * @param value - 值
   */
  static setValue<T>(obj: Record<string, any>, key: string, value: T): void {
    Reflect.set(obj, key, value);
  }

  /**
   * 获取Error的JSON字符串
   * @param error - 错误对象
   * @returns JSON字符串
   */
  static getErrorStr(error: BusinessError): string {
    const errObj: Record<string, string | number> = {
      name: error.name,
      code: error.code,
      message: error.message,
      stack: error.stack ?? '',
    };
    return JSON.stringify(errObj);
  }
}
相关推荐
╰つ栺尖篴夢ゞ8 小时前
HarmonyOS之多态样式stateStyles的使用
华为·harmonyos·statestyles·多态样式
雨白10 小时前
Jetpack Compose Navigation 2.x 详解
android·android jetpack
Android系统攻城狮13 小时前
Android内核进阶之获取DMA地址snd_pcm_sgbuf_get_addr:用法实例(九十一)
android·pcm·android内核·音频进阶·pcm硬件参数
清空mega13 小时前
Android Studio移动应用基础教程(前言)
android·ide·android studio
2501_9371454114 小时前
2025IPTV 源码优化版实测:双架构兼容 + 可视化运维
android·源码·源代码管理·机顶盒
GLAB-Mary14 小时前
HCIE最优规划路线:如何系统性学习华为认证?
学习·华为·华为认证·hcie·数通
lqj_本人15 小时前
鸿蒙Cordova插件架构与OnsenUI组件适配机制深度解析
华为·架构·harmonyos
zhoutanooi15 小时前
安卓bp文件编译学习
android·学习
aramae17 小时前
MySQL数据库入门指南
android·数据库·经验分享·笔记·mysql
Memory沙漏17 小时前
IOS如何免费申请开发者证书(uniapp开发)
ios·uni-app