# @ohos.util (util工具函数)
该模块主要提供常用的工具函数,实现字符串编解码([TextEncoder](#textencoder),[TextDecoder](#textdecoder))、有理数运算([RationalNumber8+](#rationalnumber8))、缓冲区管理([LRUCache9+](#lrucache9))、范围判断([ScopeHelper9+](#scopehelper9))、Base64编解码([Base64Helper9+](#base64helper9))、内置对象类型检查([types8+](#types8)、对方法进行插桩和替换([Aspect11+](#aspect11))等功能。
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import { util } from '@kit.ArkTS';
```
## util.format9+
format(format: string, ...args: Object[]): string
通过式样化字符串对输入的内容按特定格式输出。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------- | ---- | -------------- |
| format | string | 是 | 格式化字符串,可以包含零个或多个占位符,用于指定要插入的参数的位置和格式。 |
| ...args | Object[] | 否 | 替换format参数中占位符的数据,此参数缺失时,默认返回第一个参数。|
**返回值:**
| 类型 | 说明 |
| ------ | -----------------|
| string | 格式化后的字符串。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**格式说明符:**
| 格式说明符 | 说明 |
| ------ | -------------------------------- |
| %s | 将参数转换为字符串,用于除Object,BigInt和-0之外的所有值。|
| %d | 将参数作为十进制整数进行格式化输出,用于除Symbol和BigInt之外的所有值。|
| %i | 将字符串转换为十进制整数,用于除BigInt和Symbol之外的所有值。|
| %f | 将字符串转换为浮点数,用于除BigInt和Symbol之外的所有值。|
| %j | 将JavaScript对象转换为JSON字符串进行格式化输出。|
| %o | 用于将JavaScript对象进行格式化输出,将对象转换为字符串表示,但不包含对象的原型链信息。|
| %O | 用于将JavaScript对象进行格式化输出,将对象转换为字符串表示。|
| %c | 只在浏览器环境中有效。其余环境不会产生样式效果。|
| %% | 转义百分号的特殊格式化占位符。|
**示例:**
```ts
import { util } from '@kit.ArkTS';
interface utilAddresstype {
city: string;
country: string;
}
interface utilPersontype {
name: string;
age: number;
address: utilAddresstype;
}
let name = 'John';
let age = 20;
let formattedString = util.format('My name is %s and I am %s years old', name, age);
console.info(formattedString);
// 输出结果:My name is John and I am 20 years old
let num = 10.5;
formattedString = util.format('The number is %d', num);
console.info(formattedString);
// 输出结果:The number is 10.5
num = 100.5;
formattedString = util.format('The number is %i', num);
console.info(formattedString);
// 输出结果:The number is 100
const pi = 3.141592653;
formattedString = util.format('The value of pi is %f', pi);
console.info(formattedString);
// 输出结果:The value of pi is 3.141592653
const obj: Record = { "name": 'John', "age": 20 };
formattedString = util.format('The object is %j', obj);
console.info(formattedString);
// 输出结果:The object is {"name":"John","age":20}
const person: utilPersontype = {
name: 'John',
age: 20,
address: {
city: 'New York',
country: 'USA'
}
};
console.info(util.format('Formatted object using %%O: %O', person));
console.info(util.format('Formatted object using %%o: %o', person));
/*
输出结果:
Formatted object using %O: { name: 'John',
age: 20,
address:
{ city: 'New York',
country: 'USA' } }
Formatted object using %o: { name: 'John',
age: 20,
address:
{ city: 'New York',
country: 'USA' } }
*/
const percentage = 80;
let arg = 'homework';
formattedString = util.format('John finished %d%% of the %s', percentage, arg);
console.info(formattedString);
// 输出结果:John finished 80% of the homework
```
## util.errnoToString9+
errnoToString(errno: number): string
获取系统错误码对应的详细信息。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| errno | number | 是 | 系统发生错误产生的错误码。 |
**返回值:**
| 类型 | 说明 |
| ------ | ---------------------- |
| string | 错误码对应的详细信息。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let errnum = -1; // -1 : a system error number
let result = util.errnoToString(errnum);
console.info("result = " + result);
// 输出结果:result = operation not permitted
```
**部分错误码及信息示例:**
| 错误码 | 信息 |
| ------ | -------------------------------- |
| -1 | operation not permitted |
| -2 | no such file or directory |
| -3 | no such process |
| -4 | interrupted system call |
| -5 | i/o error |
| -11 | resource temporarily unavailable |
| -12 | not enough memory |
| -13 | permission denied |
| -100 | network is down |
## util.callbackWrapper
callbackWrapper(original: Function): (err: Object, value: Object )=>void
对异步函数进行回调化处理,回调中第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。
> **说明:**
>
> 该接口要求参数original必须是异步函数类型。如果传入的参数不是异步函数,不会进行拦截,但是会输出错误信息:"callbackWrapper: The type of Parameter must be AsyncFunction"。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| original | Function | 是 | 异步函数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Function | 返回一个回调函数,该函数第一个参数err是拒绝原因(如果 Promise 已解决,则为 null),第二个参数value是已解决的值。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
async function fn() {
return 'hello world';
}
let cb = util.callbackWrapper(fn);
cb(1, (err : Object, ret : string) => {
if (err) throw new Error;
console.info(ret);
});
// 输出结果:hello world
```
## util.promisify9+
promisify(original: (err: Object, value: Object) => void): Function
对异步函数处理并返回一个promise的函数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| original | Function | 是 | 回调函数中第一个参数err是拒绝原因(如果 Promise 已解决,则为 null),第二个参数value是已解决的值。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Function | 返回一个 Promise 的函数。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
async function fn() {
return 'hello world';
}
const addCall = util.promisify(util.callbackWrapper(fn));
(async () => {
try {
let res: string = await addCall();
console.info(res);
// 输出结果:hello world
} catch (err) {
console.info(err);
}
})();
```
## util.generateRandomUUID9+
generateRandomUUID(entropyCache?: boolean): string
使用加密安全随机数生成器生成随机的RFC 4122版本4的string类型UUID。为了提升性能,此接口会默认使用缓存,即入参为true,最多可缓存128个随机的UUID。当缓存中128个UUID都被使用后,会重新进行一次缓存UUID的生成,以保证UUID的随机性。假如不需要使用缓存的UUID,请将入参设置为false。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| entropyCache | boolean | 否 | 是否使用已缓存的UUID, 默认true。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 表示此UUID的字符串。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let uuid = util.generateRandomUUID(true);
console.info("RFC 4122 Version 4 UUID:" + uuid);
// 输出随机生成的UUID
```
## util.generateRandomBinaryUUID9+
generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array
使用加密安全随机数生成器生成随机的RFC 4122版本4的Uint8Array类型UUID。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| entropyCache | boolean | 否 | 是否使用已缓存的UUID, 默认true。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Uint8Array | 表示此UUID的Uint8Array值。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let uuid = util.generateRandomBinaryUUID(true);
console.info(JSON.stringify(uuid));
// 输出随机生成的UUID
```
## util.parseUUID9+
parseUUID(uuid: string): Uint8Array
将generateRandomUUID生成的string类型UUID转换为generateRandomBinaryUUID生成的Uint8Array类型UUID,如RFC 4122版本4中所述。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uuid | string | 是 | UUID字符串。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Uint8Array | 返回表示此UUID的Uint8Array,如果解析失败,则抛出SyntaxError。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[语言基础类库错误码](errorcode-utils.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
| 10200002 | Invalid uuid string. |
**示例:**
```ts
let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c");
console.info("uuid = " + uuid);
// 输出结果:uuid = 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156
```
## util.printf(deprecated)
printf(format: string, ...args: Object[]): string
通过式样化字符串对输入的内容按特定格式输出。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[util.format9+](#utilformat9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| format | string | 是 | 式样化字符串。 |
| ...args | Object[] | 否 | 替换式样化字符串通配符的数据,此参数缺失时,默认返回第一个参数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 按特定格式式样化后的字符串。 |
**示例:**
```ts
let res = util.printf("%s", "hello world!");
console.info(res);
// 输出结果:hello world!
```
## util.getErrorString(deprecated)
getErrorString(errno: number): string
获取系统错误码对应的详细信息。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[util.errnoToString9+](#utilerrnotostring9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| errno | number | 是 | 系统发生错误产生的错误码。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 错误码对应的详细信息。 |
**示例:**
```ts
let errnum = -1; // -1 : a system error number
let result = util.getErrorString(errnum);
console.info("result = " + result);
// 输出结果:result = operation not permitted
```
## util.promiseWrapper(deprecated)
promiseWrapper(original: (err: Object, value: Object) => void): Object
对异步函数处理并返回一个promise的版本。
> **说明:**
>
> 此接口不可用,建议使用[util.promisify9+](#utilpromisify9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| original | Function | 是 | 异步函数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Function | 采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 |
## util.getHash12+
getHash(object: object): number
获取对象的Hash值。如果是第一次获取,则计算Hash值并保存到对象的Hash域(返回随机的Hash值);如果不是第一次获取,则从Hash域中获取并返回Hash值(同一对象多次返回值保持不变)。
**原子化服务API**:从API version 12 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| object | object | 是 | 希望获取Hash值的对象。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | Hash值。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
interface Person {
name: string,
age: number
}
let obj: Person = { name: 'Jack', age: 20 };
let result1 = util.getHash(obj);
console.info('result1 is ' + result1);
let result2 = util.getHash(obj);
console.info('result2 is ' + result2);
// 输出结果:result1 与 result2 的值相等,且为随机的Hash值。
```
## TextDecoderOptions11+
解码相关选项参数,存在两个属性fatal和ignoreBOM。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
| 名称 | 类型 | 必填 | 说明 |
| --------- | -------- | ---- | ------------------ |
| fatal | boolean | 否 | 是否显示致命错误,默认值是false。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记,默认值是false。 |
## DecodeToStringOptions12+
解码是否使用流处理方式。
**原子化服务API**:从API version 12 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| stream | boolean | 否 | 输入末尾出现的不完整字节序列是否需要追加在下次调用decodeToString的参数中处理。设置为true,则不完整的字节序列会存储在内部缓存区直到下次调用该函数,false则会在当前调用时直接解码。默认为false。 |
## DecodeWithStreamOptions11+
解码是否跟随附加数据块相关选项参数。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| stream | boolean | 否 | 在随后的decodeWithStream()调用中是否跟随附加数据块。如果以块的形式处理数据,则设置为true;如果处理最后的数据块或数据未分块,则设置为false。默认为false。 |
## Aspect11+
Aspect类用于封装提供切面能力(Aspect Oriented Programming,简写AOP)的接口,这些接口可以用来对类方法进行前后插桩或者替换实现。
### addBefore11+
static addBefore(targetClass: Object, methodName: string, isStatic: boolean, before: Function): void
在指定的类对象的原方法执行前插入一个函数。addBefore接口执行完成后,都会先执行插入的函数逻辑,再执行指定类对象的原方法。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | 是 | 指定的类对象。 |
| methodName | string | 是 | 指定的方法名,不支持read-only方法。 |
| isStatic | boolean | 是 | 指定的原方法是否为静态方法,true表示静态方法,false表示实例方法。 |
| before | Function | 是 | 要插入的函数对象。函数有参数,则第一个参数是this对象(若isStatic为true,则为类对象即targetClass;若isStatic为false,则为调用方法的实例对象),其余参数是原方法的参数。函数也可以无参数,无参时不做处理。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
static data: string = 'data000';
static bar(arg: string): string {
console.info('bar arg is ' + arg);
return MyClass.data;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// 输出结果:foo arg is 123
console.info('result is ' + result);
// 输出结果:result is msg000
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg000
util.Aspect.addBefore(MyClass, 'foo', false, (instance: MyClass, arg: string) => {
console.info('arg is ' + arg);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg)
});
result = asp.foo('123');
// 输出结果:arg is 123
// 输出结果:msg is changed to msg111
// 输出结果:foo arg is 123
console.info('result is ' + result);
// 输出结果:result is msg111
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg111
let res = MyClass.bar('456');
// 输出结果:bar arg is 456
console.info('res is ' + res);
// 输出结果:res is data000
console.info('MyClass.data is ' + MyClass.data);
// 输出结果:MyClass.data is data000
util.Aspect.addBefore(MyClass, 'bar', true, (target: Object, arg: string) => {
console.info('arg is ' + arg);
let newVal = 'data111';
Reflect.set(target, 'data', newVal);
console.info('data is changed to ' + newVal);
});
res = MyClass.bar('456');
// 输出结果:arg is 456
// 输出结果:data is changed to data111
// 输出结果:bar arg is 456
console.info('res is ' + res);
// 输出结果:res is data111
console.info('MyClass.data is ' + MyClass.data);
// 输出结果:MyClass.data is data111
```
### addAfter11+
static addAfter(targetClass: Object, methodName: string, isStatic: boolean, after: Function): void
在指定的类方法执行后插入一段逻辑。最终返回值是插入函数执行后的返回值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | 是 | 指定的类对象。 |
| methodName | string | 是 | 指定的原方法名,不支持read-only方法。 |
| isStatic | boolean | 是 | 指定的原方法是否为静态方法,true表示静态方法,false表示实例方法。 |
| after | Function | 是 | 要插入的函数。函数有参数时,则第一个参数是this对象(若isStatic为true,则为类对象即targetClass;若isStatic为false,则为调用方法的实例对象),第二个参数是原方法的返回值(如果原方法没有返回值,则为undefined),其余参数是原方法的参数。函数也可以无参,无参时不做处理。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// 输出结果:foo arg is 123
console.info('result is ' + result);
// 输出结果:result is msg000
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg000
util.Aspect.addAfter(MyClass, 'foo', false, (instance: MyClass, ret: string, arg: string): string => {
console.info('arg is ' + arg);
console.info('ret is ' + ret);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg);
return 'msg222';
});
result = asp.foo('123');
// 输出结果:foo arg is 123
// 输出结果:arg is 123
// 输出结果:ret is msg000
// 输出结果:msg is changed to msg111
console.info('result is ' + result);
// 输出结果:result is msg222
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg111
// 前后插桩的例子
class AroundTest {
foo(arg: string) {
console.info('execute foo with arg ' + arg);
}
}
util.Aspect.addBefore(AroundTest, 'foo', false, () => {
console.info('execute before');
});
util.Aspect.addAfter(AroundTest, 'foo', false, () => {
console.info('execute after');
});
(new AroundTest()).foo('hello');
// 输出结果:execute before
// 输出结果:execute foo with arg hello
// 输出结果:execute after
```
### replace11+
static replace(targetClass: Object, methodName: string, isStatic: boolean, instead: Function) : void
将指定的类方法的原方法替换为另一个函数。replace接口执行完成后,调用指定的类方法时,只会执行替换后的逻辑。最终返回值为替换函数执行完毕的返回值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------- | ---- | -------------------------------------|
| targetClass | Object | 是 | 指定的类对象。 |
| methodName | string | 是 | 指定的原方法名,不支持read-only方法。 |
| isStatic | boolean | 是 | 指定的原方法是否为静态方法,true表示静态方法,false表示实例方法。 |
| instead | Function | 是 | 要用来替换原方法的函数。函数有参数时,则第一个参数是this对象(若isStatic为true,则为类对象即targetClass;若isStatic为false,则为调用方法的实例对象),其余参数是原方法的参数。函数也可以无参,无参时不做处理。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
class MyClass {
msg: string = 'msg000';
foo(arg: string): string {
console.info('foo arg is ' + arg);
return this.msg;
}
}
let asp = new MyClass();
let result = asp.foo('123');
// 输出结果:foo arg is 123
console.info('result is ' + result);
// 输出结果:result is msg000
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg000
util.Aspect.replace(MyClass, 'foo', false, (instance: MyClass, arg: string): string => {
console.info('execute instead')
console.info('arg is ' + arg);
instance.msg = 'msg111';
console.info('msg is changed to ' + instance.msg);
return 'msg222';
});
result = asp.foo('123');
// 输出结果:execute instead
// 输出结果:arg is 123
// 输出结果:msg is changed to msg111
console.info('result is ' + result);
// 输出结果:result is msg222
console.info('asp.msg is ' + asp.msg);
// 输出结果:asp.msg is msg111
```
## TextDecoder
TextDecoder用于将字节数组解码为字符串,可以处理多种编码格式,包括utf-8、utf-16le/be、iso-8859和windows-1251等不同的编码格式。
### 属性
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| encoding | string | 是 | 否 | 编码格式。
- 支持格式:utf-8、ibm866、iso-8859-2、iso-8859-3、iso-8859-4、iso-8859-5、iso-8859-6、iso-8859-7、iso-8859-8、iso-8859-8-i、iso-8859-10、iso-8859-13、iso-8859-14、iso-8859-15、koi8-r、koi8-u、macintosh、windows-874、windows-1250、windows-1251、windows-1252、windows-1253、windows-1254、windows-1255、windows-1256、windows-1257、windows-1258、x-mac-cyrillic、gbk、gb18030、big5、euc-jp、iso-2022-jp、shift_jis、euc-kr、utf-16be、utf-16le、UTF-8、GBK、GB2312、gb2312、GB18030、iso-8859-1。 |
| fatal | boolean | 是 | 否 | 是否显示致命错误。 |
| ignoreBOM | boolean | 是 | 否 | 是否忽略BOM(byte order marker)标记,默认值为false ,表示解码结果包含BOM标记。 |
### constructor9+
constructor()
TextDecoder的构造函数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**示例:**
```ts
let textDecoder = new util.TextDecoder();
let retStr = textDecoder.encoding;
console.info('retStr = ' + retStr);
// 输出结果:retStr = utf-8
```
### create9+
static create(encoding?: string, options?: TextDecoderOptions): TextDecoder
替代有参构造功能。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------ |
| encoding | string | 否 | 编码格式,默认值是'utf-8'。 |
| options | [TextDecoderOptions](#textdecoderoptions11) | 否 | 解码相关选项参数,存在两个属性fatal和ignoreBOM。|
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.encoding;
console.info('retStr = ' + retStr);
// 输出结果:retStr = utf-8
```
### decodeToString12+
decodeToString(input: Uint8Array, options?: DecodeToStringOptions): string
通过输入参数解码后输出对应文本。
**原子化服务API**:从API version 12 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| input | Uint8Array | 是 | 符合格式需要解码的数组。 |
| options | [DecodeToStringOptions](#decodetostringoptions12) | 否 | 解码相关选项参数。默认undefined。|
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 解码后的数据。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let uint8 = new Uint8Array([0xEF, 0xBB, 0xBF, 0x61, 0x62, 0x63]);
let retStr = textDecoder.decodeToString(uint8, decodeToStringOptions);
console.info("retStr = " + retStr);
// 输出结果:retStr = abc
```
### decodeWithStream(deprecated)
decodeWithStream(input: Uint8Array, options?: DecodeWithStreamOptions): string
通过输入参数解码后输出对应文本。当input是一个空数组时,返回值为undefined。
> **说明:**
>
> 从API version 9开始支持,从API version 12开始废弃,建议使用[decodeToString12+](#decodetostring12)替代。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| input | Uint8Array | 是 | 符合格式需要解码的数组。 |
| options | [DecodeWithStreamOptions](#decodewithstreamoptions11) | 否 | 解码相关选项参数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 解码后的数据。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeWithStreamOptions: util.DecodeWithStreamOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let uint8 = new Uint8Array(6);
uint8[0] = 0xEF;
uint8[1] = 0xBB;
uint8[2] = 0xBF;
uint8[3] = 0x61;
uint8[4] = 0x62;
uint8[5] = 0x63;
console.info("input num:");
let retStr = textDecoder.decodeWithStream(uint8, decodeWithStreamOptions);
console.info("retStr = " + retStr);
// 输出结果:retStr = abc
```
### constructor(deprecated)
constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean })
TextDecoder的构造函数。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[create9+](#create9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| encoding | string | 否 | 编码格式,默认值是'utf-8'。 |
| options | object | 否 | 解码相关选项参数,存在两个属性fatal和ignoreBOM。 |
**表1** options
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fatal | boolean | 否 | 是否显示致命错误,默认值是false。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记,默认值是false。 |
**示例:**
```ts
let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});
```
### decode(deprecated)
decode(input: Uint8Array, options?: { stream?: false }): string
通过输入参数解码后输出对应文本。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[decodeToString12+](#decodetostring12)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| input | Uint8Array | 是 | 符合格式需要解码的数组。 |
| options | object | 否 | 解码相关选项参数。 |
**表2** options
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| stream | boolean | 否 | 在随后的decode()调用中是否跟随附加数据块。如果以块的形式处理数据,则设置为true;如果处理最后的数据块或数据未分块,则设置为false。默认为false。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 解码后的数据。 |
**示例:**
```ts
let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true});
let uint8 = new Uint8Array(6);
uint8[0] = 0xEF;
uint8[1] = 0xBB;
uint8[2] = 0xBF;
uint8[3] = 0x61;
uint8[4] = 0x62;
uint8[5] = 0x63;
console.info("input num:");
let retStr = textDecoder.decode(uint8, {stream: false});
console.info("retStr = " + retStr);
// 输出结果:retStr = abc
```
## EncodeIntoUint8ArrayInfo11+
**系统能力:** SystemCapability.Utils.Lang
编码后的文本。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
| 名称 | 类型 | 可读 |可写 | 说明 |
| --------- | -------- | -------- |-------- |------------------ |
| read | number | 是 | 否 |表示已读取的字符数。 |
| written | number | 是 |否 |表示已写入的字节数。 |
## TextEncoder
TextEncoder用于将字符串编码为字节数组,支持多种编码格式。
需要注意的是,在使用TextEncoder进行编码时,不同编码格式下字符所占的字节数是不同的,在使用TextEncoder时需要明确指定要使用的编码格式,以确保编码结果正确。
### 属性
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| encoding | string | 是 | 否 | 编码格式。
- 支持格式:utf-8、UTF-8、GBK、GB2312、gb2312、GB18030、gb18030、ibm866、iso-8859-1、iso-8859-2、iso-8859-3、iso-8859-4、iso-8859-5、iso-8859-6、iso-8859-7、iso-8859-8、iso-8859-8-i、iso-8859-10、iso-8859-13、iso-8859-14、iso-8859-15、koi8-r、koi8-u、macintosh、windows-874、windows-1250、windows-1251、windows-1252、windows-1253、windows-1254、windows-1255、windows-1256、windows-1257、windows-1258、gbk、big5、euc-jp、iso-2022-jp、shift_jis、euc-kr、x-mac-cyrillic、utf-16be、utf-16le。
- 默认值是:'utf-8'。 |
### constructor
constructor()
TextEncoder的构造函数。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**示例:**
```ts
let textEncoder = new util.TextEncoder();
```
### constructor9+
constructor(encoding?: string)
TextEncoder的构造函数。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---- | ---- | ---- |
| encoding | string | 否 | 编码格式,默认值为'utf-8'。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let textEncoder = new util.TextEncoder("utf-8");
```
### create12+
static create(encoding?: string): TextEncoder
创建TextEncoder对象的方法。
**原子化服务API**:从API version 12 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---- | ---- | ---- |
| encoding | string | 否 | 编码格式,默认值为'utf-8'。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let textEncoder = util.TextEncoder.create("utf-8");
```
### encodeInto9+
encodeInto(input?: string): Uint8Array
通过输入参数编码后输出Uint8Array对象。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| input | string | 否 | 需要编码的字符串,默认值是空字符串。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ------------------ |
| Uint8Array | 返回编码后的Uint8Array对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
**示例:**
```ts
let textEncoder = new util.TextEncoder();
let result = textEncoder.encodeInto("\uD800¥¥");
console.info("result = " + result);
// 输出结果: result = 237,160,128,194,165,194,165
```
### encodeIntoUint8Array9+
encodeIntoUint8Array(input: string, dest: Uint8Array): EncodeIntoUint8ArrayInfo
对字符串进行编码,将结果写入dest数组。
**原子化服务API**:从API version 11 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---------- | ---- | ------------------------------------------------------- |
| input | string | 是 | 需要编码的字符串。 |
| dest | Uint8Array | 是 | Uint8Array对象实例,用于将生成的UTF-8编码文本放入其中。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ------------------ |
| [EncodeIntoUint8ArrayInfo](#encodeintouint8arrayinfo11) | 返回一个对象,read表示已编码的字符数,write表示编码字符所占用的字节数。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let textEncoder = new util.TextEncoder();
let buffer = new ArrayBuffer(4);
let uint8 = new Uint8Array(buffer);
let result = textEncoder.encodeIntoUint8Array('abcd', uint8);
console.info("uint8 = " + uint8);
// 输出结果: uint8 = 97,98,99,100
```
### encodeInto(deprecated)
encodeInto(input: string, dest: Uint8Array): { read: number; written: number }
放置生成的UTF-8编码文本。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[encodeIntoUint8Array9+](#encodeintouint8array9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| input | string | 是 | 需要编码的字符串。 |
| dest | Uint8Array | 是 | Uint8Array对象实例,用于将生成的UTF-8编码文本放入其中。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Uint8Array | 返回编码后的文本。 |
**示例:**
```ts
let textEncoder = new util.TextEncoder();
let buffer = new ArrayBuffer(4);
let uint8 = new Uint8Array(buffer);
let result = textEncoder.encodeInto('abcd', uint8);
console.info("uint8 = " + uint8);
// 输出结果: uint8 = 97,98,99,100
```
### encode(deprecated)
encode(input?: string): Uint8Array
通过输入参数编码后输出对应文本。
> **说明:**
>
> 从API version 7开始支持,从API version 9开始废弃,建议使用[encodeInto9+](#encodeinto9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| input | string | 否 | 需要编码的字符串,默认值是空字符串。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Uint8Array | 返回编码后的文本。 |
**示例:**
```ts
let textEncoder = new util.TextEncoder();
let result = textEncoder.encode("\uD800¥¥");
console.info("result = " + result);
// 输出结果: result = 237,160,128,194,165,194,165
```
## RationalNumber8+
RationalNumber主要是对有理数进行比较,获取分子分母等方法。例如使用toString()方法可以将有理数转换为字符串形式,使用该类可以方便地进行有理数的各种操作。
### constructor9+
constructor()
RationalNumber的构造函数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**示例:**
```ts
let rationalNumber = new util.RationalNumber();
```
### parseRationalNumber9+
static parseRationalNumber(numerator: number,denominator: number): RationalNumber
用于创建具有给定分子和分母的RationalNumber实例。
> **说明:**
>
> 该接口要求参数numerator和denominator必须是整数类型。如果传入的参数是小数类型,不会进行拦截,但是会输出错误信息:"parseRationalNumber: The type of Parameter must be integer"。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | ---------------- |
| numerator | number | 是 | 分子,整数类型。取值范围:-Number.MAX_VALUE <= numerator <= Number.MAX_VALUE。|
| denominator | number | 是 | 分母,整数类型。取值范围:-Number.MAX_VALUE <= denominator <= Number.MAX_VALUE。|
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
```
### createRationalFromString8+
static createRationalFromString(rationalString: string): RationalNumber
基于给定的字符串创建一个RationalNumber对象。
> **说明:**
>
> 该接口要求参数rationalString是字符串格式。如果传入的参数是小数类型字符串格式,不会进行拦截,但是会输出错误信息:"createRationalFromString: The type of Parameter must be integer string"。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| rationalString | string | 是 | 字符串格式。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Object | 返回RationalNumber对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | The type of rationalString must be string. |
**示例:**
```ts
let rational = util.RationalNumber.createRationalFromString("3/4");
```
### compare9+
compare(another: RationalNumber): number
将当前RationalNumber对象与目标RationalNumber对象进行比较,并返回比较结果。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------------- | ---- | ------------------ |
| another | [RationalNumber](#rationalnumber8) | 是 | 其他的有理数对象。 |
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------------------------------------------ |
| number | 如果两个对象相等,则返回0;如果给定对象小于当前对象,则返回1;如果给定对象大于当前对象,则返回-1。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.compare(rational);
console.info("result = " + result);
// 输出结果:result = -1
```
### valueOf8+
valueOf(): number
以整数形式或者浮点数的形式获取当前RationalNumber对象的值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回整数或者浮点数的值。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.valueOf();
console.info("result = " + result);
// 输出结果:result = 0.5
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.valueOf();
console.info("result = " + result);
// 输出结果:result = 0.5
```
### equals8+
equals(obj: Object): boolean
将当前的RationalNumber对象与给定的对象进行比较是否相等。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| obj | Object | 是 | 其他类型对象。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果给定对象与当前对象相同,则返回true;否则返回false。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.equals(rational);
console.info("result = " + result);
// 输出结果:result = false
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.equals(rational);
console.info("result = " + result);
// 输出结果:result = false
```
### getCommonFactor9+
static getCommonFactor(number1: number,number2: number): number
获取两个指定整数的最大公约数。
> **说明:**
>
> 该接口要求参数number1和number2必须是整数类型。如果传入的参数是小数类型,不会进行拦截,但是会输出错误信息:"getCommonFactor: The type of Parameter must be integer"。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ---------- |
| number1 | number | 是 | 整数类型。-Number.MAX_VALUE <= number1 <= Number.MAX_VALUE。|
| number2 | number | 是 | 整数类型。-Number.MAX_VALUE <= number2 <= Number.MAX_VALUE。|
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------------ |
| number | 返回两个给定数字的最大公约数。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let result = util.RationalNumber.getCommonFactor(4,6);
console.info("result = " + result);
// 输出结果:result = 2
```
### getNumerator8+
getNumerator(): number
获取当前RationalNumber对象的分子。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回RationalNumber对象的分子的值。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.getNumerator();
console.info("result = " + result);
// 输出结果:result = 1
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.getNumerator();
console.info("result = " + result);
// 输出结果:result = 1
```
### getDenominator8+
getDenominator(): number
获取当前RationalNumber对象的分母。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回RationalNumber对象的分母的值。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.getDenominator();
console.info("result = " + result);
// 输出结果:result = 2
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2)
let result = rationalNumber.getDenominator();
console.info("result = " + result);
// 输出结果:result = 2
```
### isZero8+
isZero():boolean
检查当前RationalNumber对象是否为0。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果当前对象表示的值为0,则返回true;否则返回false。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isZero();
console.info("result = " + result);
// 输出结果:result = false
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isZero();
console.info("result = " + result);
// 输出结果:result = false
```
### isNaN8+
isNaN(): boolean
检查当前RationalNumber对象是否表示非数字(NaN)值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果分母和分子都为0,则返回true;否则返回false。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isNaN();
console.info("result = " + result);
// 输出结果:result = false
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isNaN();
console.info("result = " + result);
// 输出结果:result = false
```
### isFinite8+
isFinite():boolean
检查当前RationalNumber对象是否表示一个有限值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | 如果分母不为0,则返回true;否则返回false。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.isFinite();
console.info("result = " + result);
// 输出结果:result = true
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.isFinite();
console.info("result = " + result);
// 输出结果:result = true
```
### toString8+
toString(): string
获取当前RationalNumber对象的字符串表示形式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| string | 返回Numerator/Denominator格式的字符串,例如3/5,如果当前对象的分子为0,则返回0/1。如果当前对象的分母为0,则返回Infinity。如果当前对象的分子和分母都为0,则返回NaN。|
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let result = rationalNumber.toString();
console.info("result = " + result);
// 输出结果:result = 1/2
```
API 9及以上建议使用以下写法:
```ts
let rationalNumber = util.RationalNumber.parseRationalNumber(1,2);
let result = rationalNumber.toString();
console.info("result = " + result);
// 输出结果:result = 1/2
```
### constructor(deprecated)
constructor(numerator: number,denominator: number)
RationalNumber的构造函数。
> **说明:**
>
> 从API version 8开始支持,从API version 9开始废弃,建议使用[parseRationalNumber9+](#parserationalnumber9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| numerator | number | 是 | 分子,整数类型。 |
| denominator | number | 是 | 分母,整数类型。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
```
### compareTo(deprecated)
compareTo(another: RationalNumber): number
将当前的RationalNumber对象与给定的对象进行比较。
> **说明:**
>
> 从API version 8开始支持,从API version 9开始废弃,建议使用[compare9+](#compare9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| another | RationalNumber | 是 | 其他的有理数对象。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 如果两个对象相等,则返回0;如果给定对象小于当前对象,则返回1;如果给定对象大于当前对象,则返回-1。 |
**示例:**
```ts
let rationalNumber = new util.RationalNumber(1,2);
let rational = util.RationalNumber.createRationalFromString("3/4");
let result = rationalNumber.compareTo(rational);
console.info("result = " + result);
// 输出结果:result = -1
```
### getCommonDivisor(deprecated)
static getCommonDivisor(number1: number,number2: number): number
获取两个指定整数的最大公约数。
> **说明:**
>
> 从API version 8开始支持,从API version 9开始废弃,建议使用[getCommonFactor9+](#getcommonfactor9)替代。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| number1 | number | 是 | 整数类型。 |
| number2 | number | 是 | 整数类型。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回两个给定数字的最大公约数。 |
## LRUCache9+
LRUCache用于在缓存空间不够的时候,将近期最少使用的数据替换为新数据。此设计基于资源访问的考虑:近期访问的数据,可能在不久的将来会再次访问。于是最少访问的数据就是价值最小的数据,是最应该踢出缓存空间的数据。
### 属性
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | ---------------------- |
| length | number | 是 | 否 | 当前缓冲区中值的总数。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(1, 8);
let result = pro.length;
console.info('result = ' + result);
// 输出结果:result = 2
```
### constructor9+
constructor(capacity?: number)
默认构造函数用于创建一个新的LRUCache实例,默认容量为64。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ---------------------------- |
| capacity | number | 否 | 指示要为缓冲区自定义的容量,不传默认值为64,最大值不能超过2147483647。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
```
### updateCapacity9+
updateCapacity(newCapacity: number): void
将缓冲区容量更新为指定容量,如果newCapacity小于或等于0,则抛出异常。当缓冲区中值的总数大于指定容量时,会执行删除操作。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | ---------------------------- |
| newCapacity | number | 是 | 指示要为缓冲区自定义的容量,最大值不能超过2147483647。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. |
**示例:**
```ts
let pro = new util.LRUCache();
pro.updateCapacity(100);
```
### toString9+
toString(): string
返回对象的字符串表示形式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------- |
| string | 返回对象的字符串表示形式。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
pro.get(3);
console.info(pro.toString());
// 输出结果:LRUCache[ maxSize = 64, hits = 1, misses = 1, hitRate = 50% ]
// maxSize: 缓存区最大值 hits: 查询值匹配成功的次数 misses: 查询值匹配失败的次数 hitRate: 查询值匹配率
```
### getCapacity9+
getCapacity(): number
获取当前缓冲区的容量。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | ---------------------- |
| number | 返回当前缓冲区的容量。 |
**示例:**
```ts
let pro = new util.LRUCache();
let result = pro.getCapacity();
console.info('result = ' + result);
// 输出结果:result = 64
```
### clear9+
clear(): void
从当前缓冲区清除键值对。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.length;
pro.clear();
let res = pro.length;
console.info('result = ' + result);
console.info('res = ' + res);
// 输出结果:result = 1
// 输出结果:res = 0
```
### getCreateCount9+
getCreateCount(): number
获取创建对象的次数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | -------------------|
| number | 返回创建对象的次数。 |
**示例:**
```ts
// 创建新类ChildLRUCache继承LRUCache,重写createDefault方法,返回一个非undefined的值。
class ChildLRUCache extends util.LRUCache {
constructor() {
super();
}
createDefault(key: number): number {
return key;
}
}
let lru = new ChildLRUCache();
lru.put(2, 10);
lru.get(3);
lru.get(5);
let res = lru.getCreateCount();
console.info('res = ' + res);
// 输出结果:res = 2
```
### getMissCount9+
getMissCount(): number
获取查询值不匹配的次数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------ |
| number | 返回查询值不匹配的次数。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
let result = pro.getMissCount();
console.info('result = ' + result);
// 输出结果:result = 0
```
### getRemovalCount9+
getRemovalCount(): number
获取缓冲区键值对回收的次数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------- |
| number | 返回缓冲区键值对回收的次数。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.updateCapacity(2);
pro.put(50, 22);
let result = pro.getRemovalCount();
console.info('result = ' + result);
// 输出结果:result = 0
```
### getMatchCount9+
getMatchCount(): number
获取查询值匹配成功的次数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------- |
| number | 返回查询值匹配成功的次数。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.get(2);
let result = pro.getMatchCount();
console.info('result = ' + result);
// 输出结果:result = 1
```
### getPutCount9+
getPutCount(): number
获取将值添加到缓冲区的次数。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------ | ---------------------------- |
| number | 返回将值添加到缓冲区的次数。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.getPutCount();
console.info('result = ' + result);
// 输出结果:result = 1
```
### isEmpty9+
isEmpty(): boolean
检查当前缓冲区是否为空。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ------- | ---------------------------------------- |
| boolean | 如果当前缓冲区不包含任何值,则返回true。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.isEmpty();
console.info('result = ' + result);
// 输出结果:result = false
```
### get9+
get(key: K): V | undefined
返回键对应的值。当键不在缓冲区中时,通过[createDefault9+](#createdefault9)接口创建,若createDefault创建的值不为undefined时,此时会调用[afterRemoval9+](#afterremoval9)接口,返回createDefault创建的值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---- | ---- | ------------ |
| key | K | 是 | 要查询的键。 |
**返回值:**
| 类型 | 说明 |
| ------------------------ | ------------------------------------------------------------ |
| V \| undefined | 如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回createDefault创建的值。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.get(2);
console.info('result = ' + result);
// 输出结果:result = 10
```
### put9+
put(key: K,value: V): V
将键值对添加到缓冲区中,返回与添加的键关联的值。当缓冲区中值的总数大于容量时,会执行删除操作。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---- | ---- | -------------------------- |
| key | K | 是 | 要添加的键。 |
| value | V | 是 | 指示与要添加的键关联的值。 |
**返回值:**
| 类型 | 说明 |
| ---- | ------------------------------------------------------------ |
| V | 返回与添加的键关联的值。如果键或值为空,则抛出此异常。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
let result = pro.put(2, 10);
console.info('result = ' + result);
// 输出结果:result = 10
```
### values9+
values(): V[]
获取当前缓冲区中所有值从最近访问到最近最少访问的顺序列表 。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| --------- | ------------------------------------------------------------ |
| V [] | 按从最近访问到最近最少访问的顺序返回当前缓冲区中所有值的列表。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(2, "anhu");
pro.put("afaf", "grfb");
let result = pro.values();
console.info('result = ' + result);
// 输出结果:result = anhu,grfb
```
### keys9+
keys(): K[]
获取当前缓冲区中所有键从最近访问到最近最少访问的升序列表。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| --------- | ------------------------------------------------------------ |
| K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(3, 1);
let result = pro.keys();
console.info('result = ' + result);
// 输出结果:result = 2,3
```
### remove9+
remove(key: K): V | undefined
从当前缓冲区中删除指定的键及其关联的值,返回键关联的值。如果键不存在时,则返回undefined。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---- | ---- | -------------- |
| key | K | 是 | 要删除的键值。 |
**返回值:**
| 类型 | 说明 |
| ------------------------ | ------------------------------------------------------------ |
| V \| undefined | 返回一个包含已删除键值对的Optional对象;如果key不存在,则返回undefined,如果key为null,则抛出异常。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.remove(20);
console.info('result = ' + result);
// 输出结果:result = undefined
```
### afterRemoval9+
afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void
删除值后执行后续操作,后续操作由开发者自行实现。本接口会在删除操作时被调用,如[get9+](#get9)、[put9+](#put9)、[remove9+](#remove9)、[clear9+](#clear9)、[updateCapacity9+](#updatecapacity9)接口。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------- | ---- | ------------------------------------------------------------ |
| isEvict | boolean | 是 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 |
| key | K | 是 | 表示删除的键。 |
| value | V | 是 | 表示删除的值。 |
| newValue | V | 是 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
class ChildLRUCache extends util.LRUCache {
constructor(capacity?: number) {
super(capacity);
}
afterRemoval(isEvict: boolean, key: K, value: V, newValue: V): void {
if (isEvict === true) {
console.info('key = ' + key);
// 输出结果:key = 1
console.info('value = ' + value);
// 输出结果:value = 1
console.info('newValue = ' + newValue);
// 输出结果:newValue = null
}
}
}
let lru = new ChildLRUCache(2);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
```
### contains9+
contains(key: K): boolean
检查当前缓冲区是否包含指定的键。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---------------- |
| key | K | 是 | 表示要检查的键。 |
**返回值:**
| 类型 | 说明 |
| ------- | ------------------------------------------ |
| boolean | 如果缓冲区包含指定的键,则返回 true。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
let result = pro.contains(2);
console.info('result = ' + result);
// 输出结果:result = true
```
### createDefault9+
createDefault(key: K): V
如果在缓冲区未匹配到键,则执行后续操作,参数表示未匹配的键,返回与键关联的值,默认返回undefined。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---- | ---- | -------------- |
| key | K | 是 | 表示未匹配的键。 |
**返回值:**
| 类型 | 说明 |
| ---- | ------------------ |
| V | 返回与键关联的值。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| -------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
**示例:**
```ts
let pro = new util.LRUCache();
let result = pro.createDefault(50);
console.info('result = ' + result);
// 输出结果:result = undefined
```
### entries9+
entries(): IterableIterator<[K,V]>
允许迭代包含在这个对象中的所有键值对。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ----------- | -------------------- |
| [K, V] | 返回一个可迭代数组。 |
**示例:**
```ts
let pro = new util.LRUCache();
pro.put(2, 10);
pro.put(3, 15);
let pair:Iterable