鸿蒙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);
  }
}
相关推荐
我的offer在哪里17 小时前
MySQL 高频细节问题(覆盖性能、存储、运维、故障排查,补充前文未深入的核心细节)
android·运维·mysql
qq_7174100117 小时前
删除设置-声音-有来电时响铃并振动,手机铃声
android
longforus17 小时前
Flutter iOS 真机部署异常经验(Android Studio 提示无法运行,但 Xcode 可正常运行)
flutter·ios·android studio
dazhong201217 小时前
Android Studio 安装之历史版本下载问题解决
android·ide·android studio
为什么不问问神奇的海螺呢丶17 小时前
n9e categraf 监控项配置文件
ios·iphone
灰度少爷17 小时前
安卓手机投屏软件——QtScrcpy!
android·智能手机·安卓手机投屏软件
2501_9159184117 小时前
iOS CPU 使用率深度分析,多工具协同定位高占用瓶颈的工程化方法
android·ios·小程序·https·uni-app·iphone·webview
啃火龙果的兔子17 小时前
android studio first run : unable to sccess android sdk add-on list
android·ide·android studio
2501_9151063217 小时前
如何防止资源文件被替换?一套针对 iOS App 的多层资源安全方案
android·安全·ios·小程序·uni-app·iphone·webview
ゞ 正在缓冲99%…18 小时前
2025.9.24华为软开
java·算法·华为