鸿蒙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);
  }
}
相关推荐
xq95271 小时前
编程之路 2025年终总结 ,勇往直前 再战江湖
harmonyos
csj501 小时前
安卓基础之《(6)—Activity组件(3)》
android
怀旧,1 小时前
【Linux系统编程】13. Ext系列⽂件系统
android·linux·缓存
Dabei1 小时前
Android 语音助手简单实现与语音助手“执行任务”交流
android·前端
jzlhll1232 小时前
android NDSDManager onResolveFailed errorCode=3的解决方案
android
柯南二号2 小时前
【大前端】【iOS】iOS 真实项目可落地目录结构方案
前端·ios
芦半山2 小时前
四年之后,重新审视 MTE:从硬件架构到工程落地
android·安全
2501_916007472 小时前
iOS与Android符号还原服务统一重构实践总结
android·ios·小程序·重构·uni-app·iphone·webview
allk552 小时前
Android 屏幕适配全维深度解析
android·性能优化·界面适配
不爱吃糖的程序媛2 小时前
鸿蒙PC命令行开发 macOS 上解决 pkg-config 命令未安装的问题
macos·华为·harmonyos