鸿蒙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);
  }
}
相关推荐
uwvwko17 分钟前
BUUCTF——web刷题第一页题解
android·前端·数据库·php·web·ctf
fzxwl26 分钟前
隆重推荐(Android 和 iOS)UI 自动化工具—Maestro
android·ui·ios
LittleLoveBoy3 小时前
踩坑:uiautomatorviewer.bat 打不开
android
居然是阿宋3 小时前
Android核心系统服务:AMS、WMS、PMS 与 system_server 进程解析
android
CGG926 小时前
【单例模式】
android·java·单例模式
kp000007 小时前
PHP弱类型安全漏洞解析与防范指南
android·开发语言·安全·web安全·php·漏洞
落叶挽歌7 小时前
鸿蒙ArkUI体验:Hexo博客客户端开发心得
华为·harmonyos
特立独行的猫a7 小时前
uni-app 开发HarmonyOS的鸿蒙影视项目分享:从实战案例到开源后台
uni-app·开源·harmonyos·鸿蒙·影视
交叉编译之王 hahaha9 小时前
RK3568-鸿蒙5.1镜像烧录与调试
华为·harmonyos
Raink老师9 小时前
鸿蒙页面布局入门
华为·harmonyos·鸿蒙·移动端布局