鸿蒙NEXT开发对象工具类ObjectUtil(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);
  }
}

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);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值