diff --git a/ArkTS/build-profile.json5 b/ArkTS/build-profile.json5 index 03ac3a3ae9dd397844173066e5d5ee21b49455a1..f762540102ab4e5209a31c7996d2f9ea9db97e36 100644 --- a/ArkTS/build-profile.json5 +++ b/ArkTS/build-profile.json5 @@ -36,6 +36,10 @@ ] } ] + }, + { + "name": "harlibrary", + "srcPath": "./harlibrary", } ] } \ No newline at end of file diff --git a/ArkTS/entry/build-profile-aot.json5 b/ArkTS/entry/build-profile-aot.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fc8e45716a58fec379b234c95b8c024fa4a16f58 --- /dev/null +++ b/ArkTS/entry/build-profile-aot.json5 @@ -0,0 +1,14 @@ +/* +* FAQ:如何开启AOT编译模式 + */ + +// [Start apPath] +{ + "apiType": 'stageMode', + "buildOption": { + "arkOptions": { + "apPath": "./entry.ap" + } + }, +} +// [End apPath] diff --git a/ArkTS/entry/oh-package.json5 b/ArkTS/entry/oh-package.json5 index 248c3b7541a589682a250f86a6d3ecf7414d2d6a..e8b46936b0b751b79c5795a837dd1c9ee45e6057 100644 --- a/ArkTS/entry/oh-package.json5 +++ b/ArkTS/entry/oh-package.json5 @@ -1,3 +1,8 @@ +/* +* FAQ:ArkTS是否支持反射调用类的静态成员函数和实例成员函数 +* FAQ:是否支持模块的动态加载?如何实现 + */ + { "name": "entry", "version": "1.0.0", @@ -5,6 +10,10 @@ "main": "", "author": "", "license": "", - "dependencies": {} + "dependencies": { + // [Start harlibrary_dep] + "harlibrary": "file:../harlibrary", + // [End harlibrary_dep] + } } diff --git a/ArkTS/entry/src/main/cpp/napi_call.cpp b/ArkTS/entry/src/main/cpp/napi_call.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e2b3e620dbcd220dedf0b67104beebdd6bc12b6 --- /dev/null +++ b/ArkTS/entry/src/main/cpp/napi_call.cpp @@ -0,0 +1,20 @@ +// +// Created on 2025/5/21. +// +// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found, +// please include "napi/native_api.h". + +static napi_value CallNapi(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value object = nullptr; + napi_status status; + status = napi_get_cb_info(env, info, &argc, &object, nullptr, nullptr); + return object; +} +NAPI_MODULE_INIT() { + napi_property_descriptor desc[] = { + { "callNapi", nullptr, CallNapi, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} \ No newline at end of file diff --git a/ArkTS/entry/src/main/cpp/napi_callback.cpp b/ArkTS/entry/src/main/cpp/napi_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3b34bae776274fde186e2ceaea00522c12ddff4 --- /dev/null +++ b/ArkTS/entry/src/main/cpp/napi_callback.cpp @@ -0,0 +1,54 @@ +// +// Created on 2025/5/21. +// +// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found, +// please include "napi/native_api.h". + +#include "napi/native_api.h" +#include +static napi_value NativeCall(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_status status; + status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + assert(status == napi_ok); + napi_valuetype valuetype; + napi_typeof(env, args[0], &valuetype); + if (valuetype != napi_valuetype::napi_function) { + napi_throw_type_error(env, nullptr, "napi_function is expected"); + } + napi_value cb = args[0]; + napi_value undefined; + status = napi_get_undefined(env, &undefined); + assert(status == napi_ok); + napi_value argv[2] = { nullptr }; + status = napi_create_int32(env, 1, &argv[0]); + assert(status == napi_ok); + status = napi_create_int32(env, 2, &argv[1]); + assert(status == napi_ok); + napi_value result; + status = napi_call_function(env, undefined, cb, 2, argv, &result); + assert(status == napi_ok); + return nullptr; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + { "nativeCall", nullptr, NativeCall, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END +static napi_module module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "callback", + .nm_priv = nullptr, + .reserved = { 0 }, +}; +extern "C" __attribute__((constructor)) void RegisterCallbackModule(void) { + napi_module_register(&module); +} \ No newline at end of file diff --git a/ArkTS/entry/src/main/cpp/napi_promise.cpp b/ArkTS/entry/src/main/cpp/napi_promise.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8f1e50cd3e6661ba40828e1daaea84d2441f760 --- /dev/null +++ b/ArkTS/entry/src/main/cpp/napi_promise.cpp @@ -0,0 +1,113 @@ +// +// Created on 2025/5/21. +// +// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found, +// please include "napi/native_api.h". + +#include "napi/native_api.h" +// Empty value so that macros here are able to return NULL or void +#define NAPI_RETVAL_NOTHING // Intentionally blank +#define GET_AND_THROW_LAST_ERROR(env) + do { + const napi_extended_error_info* errorInfo = nullptr; + napi_get_last_error_info((env), &errorInfo); + bool isPending = false; + napi_is_exception_pending((env), &isPending); + if (!isPending && errorInfo != nullptr) { + const char* errorMessage = + errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; + napi_throw_error((env), nullptr, errorMessage); + } + } while (0) +#define NAPI_ASSERT_BASE(env, assertion, message, retVal) + do { + if (!(assertion)) { + napi_throw_error((env), nullptr, "assertion ("#assertion") failed:" message); + return retVal; + } + } while (0) +#define NAPI_ASSERT(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, nullptr) +#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) + NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING) +#define NAPI_CALL_BASE(env, theCall, retVal) + do { + if ((theCall) != napi_ok) { + GET_AND_THROW_LAST_ERROR((env)); + return retVal; + } + } while (0) +#define NAPI_CALL(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr) +#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING) +struct AsyncData { + napi_deferred deferred; + napi_async_work work; + int32_t arg; + double retVal; +}; +double DoSomething(int32_t val) { + if (val != 0) { + return 1.0 / val; + } + return 0; +} +void ExecuteCallback(napi_env env, void* data) { + AsyncData* asyncData = reinterpret_cast(data); + asyncData->retVal = DoSomething(asyncData->arg); +} +void CompleteCallback(napi_env env, napi_status status, void* data) { + AsyncData* asyncData = reinterpret_cast(data); + napi_value retVal; + if (asyncData->retVal == 0) { + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "arg can't be zero", NAPI_AUTO_LENGTH, &retVal)); + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncData->deferred, retVal)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_create_double(env, asyncData->retVal, &retVal)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncData->deferred, retVal)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, asyncData->work)); + asyncData->work = nullptr; + asyncData->deferred = nullptr; + delete asyncData; +} +static napi_value NativeCall(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + int32_t arg; + NAPI_CALL(env, napi_get_value_int32(env, args[0], &arg)); + // Create promise + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + AsyncData* data = new AsyncData; + data->deferred = deferred; + data->arg = arg; + napi_async_work work; + napi_value workName; + napi_create_string_utf8(env, "promise", NAPI_AUTO_LENGTH, &workName); + NAPI_CALL(env, napi_create_async_work(env, nullptr, workName,ExecuteCallback, CompleteCallback, data, &work)); + data->work = work; + NAPI_CALL(env, napi_queue_async_work(env, work)); + return promise; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + { "nativeCall", nullptr, NativeCall, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "promise", + .nm_priv = nullptr, + .reserved = { 0 }, +}; +extern "C" __attribute__((constructor)) void RegisterPromiseModule(void) { + napi_module_register(&demoModule); +} \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/AOPReplaced.ets b/ArkTS/entry/src/main/ets/pages/AOPReplaced.ets new file mode 100644 index 0000000000000000000000000000000000000000..aef4e458ca90535d2f991f0ef261a49cd97d5372 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/AOPReplaced.ets @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何判断能否对接口进行插桩或替换 + */ + +// [Start replaced] +import { ObjectUtil } from '../utils/ObjectUtil' + +class Test { + static data: string = "initData"; + static printData(): void { + console.log("execute original printData"); + } +} + +@Entry +@Component +export struct AOPReplaced { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + // 获取 myMethod 的属性描述符 + let des = ObjectUtil.ObjectGetOwnPropertyDescriptor(Test, 'printData') + console.log('des',JSON.stringify(des)) + // 判断 writable 字段是否为 true + if (des && des.writable) { + console.log('Method is writable'); + } else { + console.log('Method is not writable or does not exist'); + } + }) + } + .width('100%') + } + .height('100%') + } +} +// [End replaced] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/AddBefore.ets b/ArkTS/entry/src/main/ets/pages/AddBefore.ets new file mode 100644 index 0000000000000000000000000000000000000000..950dff9f8e6925cb863a5a2c21a428fd0b8a56df --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/AddBefore.ets @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用AOP接口实现重复插桩或替换 + */ + +// [Start add_before] +import { util } from '@kit.ArkTS'; + +class Test { + static data: string = "initData"; + + static printData(): void { + console.log("execute original printData"); + } +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + Test.printData(); + util.Aspect.addBefore(Test, "printData", true, (classObj: Test) => { + console.log("execute before 1"); + }); + Test.printData(); + util.Aspect.addBefore(Test, "printData", true, (classObj: Test) => { + console.log("execute before 2"); + }); + util.Aspect.addBefore(Test, "printData", true, (classObj: Test) => { + console.log("execute before 3"); + }); + Test.printData(); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End add_before] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/AopUtils.ets b/ArkTS/entry/src/main/ets/pages/AopUtils.ets new file mode 100644 index 0000000000000000000000000000000000000000..3faa95513d9e9cf5c7a8a385a6be374898b5fc2c --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/AopUtils.ets @@ -0,0 +1,65 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何通过AOP统计方法执行时间 + */ + +// [Start aop_utils] +import { util } from '@kit.ArkTS'; +import { systemDateTime } from '@kit.BasicServicesKit'; + +class Utils { + Add(len: number): number { + let num = 0; + for (let index = 1; index <= len; index++) { + num += index; + } + return num; + } +} + +let startTime = 0; // Initialization start time +let endTime = 0; // Initialization end time + +util.Aspect.addBefore(Utils, 'Add', false, () => { + startTime = systemDateTime.getTime(true); // Return the start time in nanoseconds +}) + +util.Aspect.addAfter(Utils, 'Add', false, () => { + endTime = systemDateTime.getTime(true); // Return the end time in nanoseconds +}) + +let utilsObj = new Utils(); +utilsObj.Add(1000); + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button('get execution time') + .onClick(() => { + console.log('startTime:', startTime); + console.log('endTime:', endTime); + console.log('endTime - startTime = ', endTime - startTime); + }) + } + .width('100%') + }.height('100%') + } +} +// [End aop_utils] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/AreaSize.ets b/ArkTS/entry/src/main/ets/pages/AreaSize.ets new file mode 100644 index 0000000000000000000000000000000000000000..f685d2d48f33078dbecdcb7ace2d8cc094296d16 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/AreaSize.ets @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS是否支持多继承 + */ + +// [Start area_size] +class TestClassA { + address: string = ''; +} + +class TestClassB { + name: string = ''; +} + +// report errors:Classes can only extend a single class. +// class TestClassC extends TestClassA, TestClassB { +// } + +interface AreaSize { + calculateAreaSize(): number; +} + +interface Cal { + Sub(a: number, b: number): number; +} + +interface Area extends AreaSize, Cal { + areaName: string; + length: number; + width: number; +} +// [End area_size] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ArrayList1.ets b/ArkTS/entry/src/main/ets/pages/ArrayList1.ets new file mode 100644 index 0000000000000000000000000000000000000000..66bf73abad90e2a085ef763e38ac9cb7ab5362f0 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/ArrayList1.ets @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何通过Index获取ArrayList中的元素 + */ + +// [Start array_list] +import { ArrayList } from '@kit.ArkTS'; + +let arrayList: ArrayList = new ArrayList(); +arrayList.add(0); +arrayList.add(1); +arrayList.add(2); +arrayList.add(3); +arrayList.add(4); +arrayList.add(5); +arrayList.add(6); +arrayList.add(7); +arrayList.add(8); +arrayList.add(9); + +@Entry +@Component +struct Index { + @State message: string = 'get arrayList value'; + + build() { + Row() { + Column() { + Button(this.message) + .onClick(() => { + console.info('arrayList[6]:', arrayList[6]); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End array_list] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ArrayList2.ets b/ArkTS/entry/src/main/ets/pages/ArrayList2.ets new file mode 100644 index 0000000000000000000000000000000000000000..8ccc5185c854ef2a436c57a6803bae77344b2e1d --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/ArrayList2.ets @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何通过Index获取ArrayList中的元素 + */ + +// [Start array_list2] +import { ArrayList } from '@kit.ArkTS'; + +let arrayList: ArrayList = new ArrayList(); +arrayList.add(0); +arrayList.add(1); +arrayList.add(2); +arrayList.add(3); +arrayList.add(4); +arrayList.add(5); +arrayList.add(6); +arrayList.add(7); +arrayList.add(8); +arrayList.add(9); + +let result: ArrayList = arrayList.subArrayList(2, 4); + +@Entry +@Component +struct Index { + @State message: string = 'subArrayList result'; + + build() { + Row() { + Column() { + Button(this.message) + .onClick(() => { + console.info('subArrayList result:', JSON.stringify(result)); // subArrayList result {"0":"2","1":"3"} + }) + } + .width('100%') + } + .height('100%') + } +} +// [End array_list2] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/Assign.ets b/ArkTS/entry/src/main/ets/pages/Assign.ets new file mode 100644 index 0000000000000000000000000000000000000000..be7f4f67bedc378d85236cedaea09cbfa16b237f --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/Assign.ets @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何合并两个对象 + */ + +// [Start assign] +function assign(target: Record, ...source: Object[]): Record { + for (const items of source) { + for (const key of Object.keys(items)) { + target[key] = Reflect.get(items, key) + } + } + return target; +} +// [End assign] + +// [Start i_merge_sub] +interface IMergeSub { + testString: string, + testObject?: IMergeSub, + testArray?: Array +} + + +interface IMerge { + a: IMergeSub, + b: IMergeSub[], + c: string[], + d: number +} + + +export function testAssign() { + let objectOne: IMerge = + { + a: { + testString: 'objectOne-a-testString', + testObject: { + testString: 'objectOne-a-testObject-testString' + }, + testArray: [1] + }, + b: [{ + testString: 'objectOne-b-testString', + testObject: { + testString: 'objectOne-b-testObject-testString' + }, + testArray: [2] + }], + c: ['objectOne-c'], + d: 3 + } + + + let objectTwo: Record = { + 'a': 'objectTwo-a', + 'c': ['objectTwo-c'], + 'e': 1 + } + + + let objectThree: Record = { + 'f': ['objectThree-f'] + } + + + // Merge multiple objects, and the properties of both Object One and Object Two will be attached to Object Three. When the property names are the same, the properties of the object with the lower index will overwrite the properties of the previous object + const multiObjectMerged = assign(objectThree, objectTwo, objectOne); + console.log('multiObjectMerged is:' + JSON.stringify(multiObjectMerged)); + console.log('objectThree is:' + JSON.stringify(objectThree)); + + + // Merge the properties of Object One into Object Two, and the value of Object Two will change. When the property names are the same, Object One will overwrite the properties of Object Two + const objectMerged = assign(objectTwo, objectOne); + console.log('objectTwo is:' + JSON.stringify(objectTwo)); + console.log('objectMerged is:' + JSON.stringify(objectMerged)); +} +// [End i_merge_sub] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/Base64Encode.ets b/ArkTS/entry/src/main/ets/pages/Base64Encode.ets new file mode 100644 index 0000000000000000000000000000000000000000..de35194388106c20bca83cad5b529debdf793645 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/Base64Encode.ets @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何进行base64编码 + */ + +// [Start base64_encode] +import { util } from '@kit.ArkTS'; + +@Entry +@Component +struct Base64Encode { + @State message: string = 'Base64 encoding'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let base64 = new util.Base64Helper(); + let arr = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56]); + let base64Str = base64.encodeToStringSync(arr); // Uint8Array to base64 + console.log('encodeToStringSync',base64Str); + // base64.decodeSync(''); // base64 to Uint8Array + // console.log('decodeSync',base64.decodeSync('')); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End base64_encode] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/BigIntNum.ets b/ArkTS/entry/src/main/ets/pages/BigIntNum.ets new file mode 100644 index 0000000000000000000000000000000000000000..a70108d195a32d1c29ecc75e546c76187262b0bc --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/BigIntNum.ets @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何处理大整数 + */ + +// [Start big_int_num] +@Entry +@Component +struct BigIntNum { + build() { + Row() { + Column() { + Button('BigInt num') + .onClick(() => { + let bigIntNum: bigint = 12345678901234567890n; // Add n suffix after integer + let anotherBigInt: bigint = BigInt(9007199254740992); // Use BigInt() constructor + let sumBigInt: bigint = bigIntNum + anotherBigInt; + console.info('bigIntNum:' + bigIntNum); + console.info('anotherBigInt:' + anotherBigInt); + console.info('bigIntNum + anotherBigInt:' + sumBigInt); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End big_int_num] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/Buffer.ets b/ArkTS/entry/src/main/ets/pages/Buffer.ets new file mode 100644 index 0000000000000000000000000000000000000000..cebcb9cbf2bf6ca15258659e446c7ac1e0775f4d --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/Buffer.ets @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS中有类似java中的System.arraycopy数组复制的方法吗 + */ + +// [Start buffer] +import { buffer } from '@kit.ArkTS'; + +let buf1 = buffer.from("1234"); +let buf2 = buffer.from("abcd"); +let buf = buffer.concat([buf1, buf2]); +console.info(buf.toString('hex')); +// Output result:3132333461626364 +// [End buffer] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/DetermineObjectType.ets b/ArkTS/entry/src/main/ets/pages/DetermineObjectType.ets new file mode 100644 index 0000000000000000000000000000000000000000..ee426fcfe85e84e44ab1dcb77d1b0ee71e9f0fa3 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/DetermineObjectType.ets @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何判断对象的类型 + */ + +// [Start determine_object_type] +class BaseClass { + value: number = 0; + + + printf() { + console.info('base value:' + this.value); + } + + + setValue(val: number) { + this.value = val; + } +} + + +class AClass extends BaseClass { + value: number = 1; + + + setValue(val: number) { + this.value = val; + } + + + getValue(): number { + return this.value; + } +} + + +class BClass extends BaseClass { + value: number = 2; + + + setValue(val: number) { + this.value = val; + } +} + + +function printValue(base: BaseClass) { + base.printf(); + let flag = base instanceof AClass; + console.info('printValue flag:' + flag); + if (flag) { + let val = (base as AClass).getValue(); + console.info('printValue val:' + val); + } +} + + +@Entry +@Component +struct DetermineObjectType { + aboutToAppear(): void { + printValue(new AClass()); + printValue(new BClass()); + } + + + build() { + } +} +// [End determine_object_type] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/DynamicImport.ets b/ArkTS/entry/src/main/ets/pages/DynamicImport.ets new file mode 100644 index 0000000000000000000000000000000000000000..ef455929b06612c7e39fa7f7d94bd6d6b0a8d794 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/DynamicImport.ets @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何实现类似Java中的反射方法调用能力 + */ + +// [Start module] +import('./module').then( + module => { + const t = module.DataTable.tagName(); + }); +// [End module] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/Entries.ets b/ArkTS/entry/src/main/ets/pages/Entries.ets new file mode 100644 index 0000000000000000000000000000000000000000..4b64549ed5edda39466cca364e9c6d3087cb1765 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/Entries.ets @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何遍历JSON对象 + */ + +// [Start entries] +import { ArrayList } from '@kit.ArkTS'; + + +interface Winner { num: number }; +let tmpStr: Record = JSON.parse('{ "0": {"num": 1}, "1": {"num": 2} }'); +const arrayList: ArrayList = new ArrayList(); +Object.entries(tmpStr).forEach((item) => { + const value = item[1]; + arrayList.add(value); +}) +// [End entries] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/EventTestExample.ets b/ArkTS/entry/src/main/ets/pages/EventTestExample.ets new file mode 100644 index 0000000000000000000000000000000000000000..c129e17bb4dccd4a182a4fc3011924004e2fc3f7 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/EventTestExample.ets @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:.ets文件和.ts文件的区别及如何互相调用文件中定义的方法 + */ + +// [Start event_test] +// Introduce the method defined in the ts file +import test from './ExportTest'; + +@Entry +@Component +struct eventTestExample { + build() { + Button('test') + .onClick(() => { + test(); // Call the methods defined in the ts file + }) + } +} +// [End event_test] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ExportTest.ts b/ArkTS/entry/src/main/ets/pages/ExportTest.ts new file mode 100644 index 0000000000000000000000000000000000000000..acdce4f8096f9ba63018f53e37b91a91c752ebdb --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/ExportTest.ts @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:.ets文件和.ts文件的区别及如何互相调用文件中定义的方法 + */ + +// [Start test] +// Declare and export the method 'test' for external file import calls +export default function test() { + // to do something +} +// [End test] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/GetObjectAllFun.ets b/ArkTS/entry/src/main/ets/pages/GetObjectAllFun.ets new file mode 100644 index 0000000000000000000000000000000000000000..9fa2251790815d9d985876a376084d0d78b8f421 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/GetObjectAllFun.ets @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何获取对象的所有方法 + */ + +// [Start get_object_all] +import { testClass } from '../utils/testClass'; + + +let protoType = testClass.prototype; +let methodsName: string[] = Object.getOwnPropertyNames(protoType); +console.info(methodsName.toString()); + + +@Entry +@Component +struct GetObjectAllFun { + @State message: string = 'Hello World'; + + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +// [End get_object_all] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/HarlibraryIndex.ets b/ArkTS/entry/src/main/ets/pages/HarlibraryIndex.ets new file mode 100644 index 0000000000000000000000000000000000000000..559b30d12086d854ac521fbcd8f7b48e8ca7ac65 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/HarlibraryIndex.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS是否支持反射调用类的静态成员函数和实例成员函数 +* FAQ:是否支持模块的动态加载?如何实现 + */ + +// [Start harlibrary_index] +// HAP's Index.ets +import('harlibrary').then((ns:ESObject) => { + ns.Calc.staticAdd(8, 9); // Call static member functions staticAdd() + let calc:ESObject = new ns.Calc(); // Instantiate class Calc + calc.instanceAdd(10, 11); // Call member functions instanceAdd() + ns.addHarlibrary(6, 7); // Call global methods addHarlibrary() + + // Use string names of classes, member functions, and methods for reflection calls + let className = 'Calc'; + let methodName = 'instanceAdd'; + let staticMethod = 'staticAdd'; + let functionName = 'addHarlibrary'; + ns[className][staticMethod](12, 13); // Call static member functions staticAdd() + let calc1:ESObject = new ns[className](); // Instantiate class Calc + calc1[methodName](14, 15); // Call member functions instanceAdd() + ns[functionName](16, 17); // Call global methods addHarlibrary() +}); +// [End harlibrary_index] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/HashMapFile.ets b/ArkTS/entry/src/main/ets/pages/HashMapFile.ets new file mode 100644 index 0000000000000000000000000000000000000000..6dae55543a4af63e4eb899534f1a2050feddbbc0 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/HashMapFile.ets @@ -0,0 +1,61 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将JSON对象转换成HashMap + */ + +// [Start hash_map] +import { HashMap } from '@kit.ArkTS'; + +let str: string = '{\"common_params\": {' + + '\"city_id\": 1,' + + '\"nav_id_list\": \"\",' + + '\"show_hook_card\": 2,' + + '\"use_one_stop_structure\": 1,' + + '\"version_tag\": \"homepageonestop\"' + + '}' + + '}'; + +let jsonObj: Object = JSON.parse(str); +let commObj = (jsonObj as Record); +let commRecord = (commObj['common_params'] as Record); +let keyStr = Object.keys(commRecord); + +for (let index: number = 0; index < keyStr.length; index++) { + commRecord[keyStr[index].toString()].toString(); +} + +let hashMapData: HashMap = new HashMap(); +hashMapData.set('common_params', commRecord); + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button('JSON to HashMap') + .onClick(() => { + // common_params: {"city_id":1,"nav_id_list":"","show_hook_card":2,"use_one_stop_structure":1,"version_tag":"homepageonestop"} + console.log('common_params:', JSON.stringify(hashMapData.get('common_params'))); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End hash_map] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/KeyObject.ets b/ArkTS/entry/src/main/ets/pages/KeyObject.ets new file mode 100644 index 0000000000000000000000000000000000000000..e1555c20a754e673d635b85ade2e234f78ba8aec --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/KeyObject.ets @@ -0,0 +1,43 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何通过key获取对象值 + */ + +// [Start key_object ] +class Student { + data: Record = { 'name': 'aaa', 'age': 'bbb' }; +} + + +@Entry +@Component +struct KeyObject { + build() { + Column() { + Button('click') + .onClick(() => { + let student = new Student(); + console.info(`${student.data['name']}`); + }) + } + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .width('100%') + .height('100%') + } +} +// [End key_object] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/MapSource.ets b/ArkTS/entry/src/main/ets/pages/MapSource.ets new file mode 100644 index 0000000000000000000000000000000000000000..5c19db61e2f04b6bf47944a181b926981cf6beca --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/MapSource.ets @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将Map转换为JSON字符串 + */ + +// [Start map_source] +let mapSource = new Map(); +mapSource.set('name', 'name1'); +mapSource.set('width', '100'); +mapSource.set('height', '50'); + +let jsonObject: Record = {}; +mapSource.forEach((value, key) => { + if (key !== undefined && value !== undefined) { + jsonObject[key] = value; + } +}) +let jsonInfo: string = JSON.stringify(jsonObject); + +@Entry +@Component +struct Index { + build() { + Column() { + Button('Map to JSON') + .onClick(() => { + console.log('jsonInfo:', jsonInfo); // jsonInfo: {"name":"name1","width":"100","height":"50"} + }) + } + } +} +// [End map_source] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/MetaData.ets b/ArkTS/entry/src/main/ets/pages/MetaData.ets new file mode 100644 index 0000000000000000000000000000000000000000..891a236621d8bac920e071393a7a924da98faee8 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/MetaData.ets @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在ArkTS中实现运行时注解的能力 + */ + +// [Start metadata] +import "reflect-metadata"; + +// The ability of third-party packaging is exposed in Reflect +@Reflect.metadata("TargetClass", 'classData') + // Tag class, key is "targetClass", data is classData +class MyClass { + @Reflect.metadata("TargetMethod", 'methodData') + // Tag method, key is' Target Method ', data is' methodData' + myMethod() { + } + + @Reflect.metadata("Static", 'staticData') + static invoke() { + } +} + +// Retrieve tag information at runtime +console.info(Reflect.getMetadata("TargetClass", MyClass)); //classData +console.info(Reflect.getMetadata("TargetMethod", new MyClass(), "myMethod")); //methodData +console.info(Reflect.getMetadata("Static", MyClass, "invoke")); // staticData +// [End metadata] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/MyDescriptorCom.ets b/ArkTS/entry/src/main/ets/pages/MyDescriptorCom.ets new file mode 100644 index 0000000000000000000000000000000000000000..a8ee90f478b15d4c5b60501d443442c5f87e5b74 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/MyDescriptorCom.ets @@ -0,0 +1,58 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在ArkTS中实现自定义装饰器能力 + */ + +// [Start my_descriptor] +function MyDescriptor(target: Object, key: string, descriptor: PropertyDescriptor) { + const originalMethod: Function = descriptor.value + descriptor.value = (...args: Object[]) => { + // Get the name, input parameters, and return value of the decorated method + console.log(`Calling ${target.constructor.name} method ${key} with argument: ${args}`) + const result: Object = originalMethod(...args) + console.log(`Method ${key} returned: ${result}`) + return result + } + return descriptor +} + +@Entry +@Component +export struct MyDescriptorCom { + @State message: string = 'Hello World'; + + @MyDescriptor + demoFunc(str:string) { + return str + } + + aboutToAppear(): void { + this.demoFunc('DemoTest') + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +// [End my_descriptor] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ParamsType.ets b/ArkTS/entry/src/main/ets/pages/ParamsType.ets new file mode 100644 index 0000000000000000000000000000000000000000..c1566266092dd1bcb4904b94665bad219ea86cbd --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/ParamsType.ets @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何通过判断函数入参类型实现不同代码逻辑 + */ + +// [Start params_type] +class Game { +} + + +function solve(message: number | string | boolean | Map | Record | Game) { + // Game:Type judgment + if (message instanceof Game) { + console.info('Game'); + return; + } + + + // Retrieve the constructor corresponding to the parameter and convert it to a string, then extract the string + let typeStr: string = message.constructor.toString().substring(9, 12); + // Determine the type corresponding to typeStr + switch (typeStr) { + case 'Num': + console.info('number type'); + break; + case 'Str': + console.info('string type'); + break; + case 'Boo': + console.info('boolean type'); + break; + case 'Map': + console.info('Map type'); + break; + case 'Obj': + console.info('Record type'); + break; + } +} + + +let gameVal: Game = ''; +let mapVal = new Map(); +mapVal.set('width', 100); +mapVal.set('height', 100); +let recordVal: Record = { 'wight': 100, 'score': 100 }; + + +@Entry +@Component +struct ParamsType { + build() { + Row() { + Column() { + Button('get params type') + .onClick(() => { + solve(100); + solve('100'); + solve(true); + solve(mapVal); + solve(recordVal); + solve(gameVal); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End params_type] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ReflectBoundThis.ets b/ArkTS/entry/src/main/ets/pages/ReflectBoundThis.ets new file mode 100644 index 0000000000000000000000000000000000000000..efb4ba3d1bee4485489c122b4ae7cc0da4e5917d --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/ReflectBoundThis.ets @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在ArkTS使用Reflect正确绑定this指针 + */ + +// [Start reflect_class] +class ReflectClass { + private a = 'a'; + + + get getA() { + return () => { + return this.a; + }; + } + + + set setA(a: string) { + this.a = a; + } +} + + +function testInvoke() { + const reflectClass = new ReflectClass(); + const fn: Function = Reflect.get(reflectClass, 'getA', reflectClass); + console.info(fn()); +} + + +@Entry +@Component +struct ReflectBoundThis { + aboutToAppear(): void { + testInvoke(); + } + + + build() { + } +} +// [End reflect_class] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TaskPoolContrast.ets b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast.ets new file mode 100644 index 0000000000000000000000000000000000000000..177f3e90a324cf477a41c3aff25edfa70efb2b09 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast.ets @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将类Java语言的线程模型(内存共享)的实现方式转换成在ArkTS的线程模型下(内存隔离)的实现方式 + */ + +// [Start run1] +import { taskpool } from '@kit.ArkTS'; + +@Concurrent +function run(args: number) { + // Do some independent tasks +} +let task: taskpool.Task = new taskpool.Task(run, 100); // 100: test number +taskpool.execute(task).then((res) => { + // Return result +}); +// [End run1] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TaskPoolContrast2.ets b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast2.ets new file mode 100644 index 0000000000000000000000000000000000000000..56f02d946484bf31f4a830f7630711390e0ae3be --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast2.ets @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将类Java语言的线程模型(内存共享)的实现方式转换成在ArkTS的线程模型下(内存隔离)的实现方式 + */ + +// [Start run2] +import { taskpool } from '@kit.ArkTS'; + +@Concurrent +function runner(material: Material): void { + return material.action(100); // 100: test number +} +@Sendable +class Material { + action(args: number) { + // Do some independent tasks + } +} +let material = new Material() +taskpool.execute(runner, material).then((ret) => { + // Return result +}) +// [End run2] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TaskPoolContrast3.ets b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast3.ets new file mode 100644 index 0000000000000000000000000000000000000000..ceb6dcd8260e971ada770b26949bf5f94b171260 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast3.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将类Java语言的线程模型(内存共享)的实现方式转换成在ArkTS的线程模型下(内存隔离)的实现方式 + */ + +// [Start run3] +import taskpool from '@ohos.taskpool' + +// let result: Object[] | undefined = undefined + +@Concurrent +function runner(task:Task) { + task.run() +} +@Sendable +class Task { + run(args?: Object[] | undefined) { + // Do some independent tasks + taskpool.Task.sendData(JsResult) + } +} +let task = new Task() +let run = new taskpool.Task(runner, task) +run.onReceiveData((result?: Function | undefined) => { + UpdateUI(result) +}) +taskpool.execute(run).then((ret) => { + // Return result +}) +// [End run3] + +function UpdateUI(result?: Function | undefined) { + throw new Error('Function not implemented.') +} + diff --git a/ArkTS/entry/src/main/ets/pages/TaskPoolContrast4.ets b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast4.ets new file mode 100644 index 0000000000000000000000000000000000000000..4c027a1e017bdb2864506fec97be69d8f458036d --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TaskPoolContrast4.ets @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将类Java语言的线程模型(内存共享)的实现方式转换成在ArkTS的线程模型下(内存隔离)的实现方式 + */ + +// [Start run4] +import { MessageEvents, taskpool, worker } from '@kit.ArkTS'; +class SdkU3d { + static getInst(): Object { + return SdkMgr.getInst(); + } + getPropStr(str: string) { } +} +let workerInstance = new worker.ThreadWorker("xx/worker.ts"); +workerInstance.registerGlobalCallObject("instance_xx", SdkU3d.getInst()); +workerInstance.postMessage("start"); +// In the game worker thread +const mainPort = worker.workerPort; +mainPort.onmessage = (e: MessageEvents): void => { + let ret = mainPort.callGlobalCallObjectMethod("instance_xx", "getPropStr", 100); // 100: test number +} +// [End run4] + +class SdkMgr { + static getInst(): Object { + return new SdkMgr(); + } +} \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TestJSON.ets b/ArkTS/entry/src/main/ets/pages/TestJSON.ets new file mode 100644 index 0000000000000000000000000000000000000000..70964fb6b3a75876c51eb5ff3cb456d0385c04b1 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TestJSON.ets @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何解析JSON字符串为实例对象 + */ + +// [Start test_json] +import { Type, plainToClass } from 'class-transformer' +import "reflect-metadata" + +// Assuming accepted JSON data +let testJSON: Record = { + 'id': 1, + 'firstName': "Johny", + 'lastName': "Cage", + 'age': 27, + 'arr': [ + { + 'name': 'john' + }, + { + 'name': 'tom' + } + ], + 'instanceA': { + 'name': 'john' + }, +} + +// If there is a corresponding nested structure, the corresponding type needs to be specified +class A { + name: string = 'john'; + + getName(): string { + return this.name + } +} + +// When attempting to convert an object with nested objects, it is necessary to know the object type to be converted and use the @ Type decorator to implicitly specify the object type contained in each attribute +class User { + id: number = 0; + firstName: string = ''; + lastName: string = ''; + age: number = 0; + @Type(() => A) + arr: A[] = [new A()] + @Type(() => A) + instanceA: A = new A(); + + getName() { + return this.firstName + " " + this.lastName; + } + + isAdult() { + return this.age > 36 && this.age < 60; + } +} + +@Entry +@Component +struct parsingJSONStringsIntoInstanceObjects { + aboutToAppear(): void { + const instance = plainToClass(User, testJSON); + console.info('instance:' + JSON.stringify(instance)) + } + + build() { + + } +} +// [End test_json] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TestStatic.ets b/ArkTS/entry/src/main/ets/pages/TestStatic.ets new file mode 100644 index 0000000000000000000000000000000000000000..82d6bfda2bd5240e7ac5bc20d9fac7a01cca6b49 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TestStatic.ets @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何访问类的静态变量和方法 + */ + +// [Start test_static] +// Accessing static variables or executing static methods +class TestStatic { + static aaa: string = '3333'; + + static getAAA () { + // console.log(this.aaa) Static variables cannot be accessed through this and can only be used in static methods + return TestStatic.aaa; + } +} +TestStatic.aaa; +// [End test_static] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TextDecoder.ets b/ArkTS/entry/src/main/ets/pages/TextDecoder.ets new file mode 100644 index 0000000000000000000000000000000000000000..59a8d87b4bf97859e7fabfe6f21e5fa53b85b1e3 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TextDecoder.ets @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将ArrayBuffer转成string + */ + +// [Start array_buffer] +import { util, buffer } from '@kit.ArkTS'; + +let blobValue: buffer.Blob = new buffer.Blob(['name', 'age', 'sex']); +let proArrayBuffer = blobValue.arrayBuffer(); + +proArrayBuffer.then((arrayBufferVal: ArrayBuffer) => { + let decoder = util.TextDecoder.create('utf-8'); + let stringData = decoder.decodeToString(new Uint8Array(arrayBufferVal)); + console.log('stringData:', stringData); +}); +// [End array_buffer] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/TextEncoder.ets b/ArkTS/entry/src/main/ets/pages/TextEncoder.ets new file mode 100644 index 0000000000000000000000000000000000000000..701183f1707a4f680174ebe8b0ab4b179fd84ef8 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/TextEncoder.ets @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何实现字符串编解码 + */ + +// [Start text_encoder] +import { util } from '@kit.ArkTS'; +// Create Encoder +let textEncoder:util.TextEncoder = new util.TextEncoder('gbk'); +let buffer:ArrayBuffer = new ArrayBuffer(20); +let encodeResult:Uint8Array = new Uint8Array(buffer); + + +// code +encodeResult = textEncoder.encodeInto('hello'); +console.info('Encode result: ', encodeResult); + + +// Create decoder +let textDecoder = util.TextDecoder.create('gbk'); + + +// decode +let decodeResult = textDecoder.decodeToString(encodeResult); +console.info('Decode result: ', decodeResult); +// [End text_encoder] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/UintArray.ets b/ArkTS/entry/src/main/ets/pages/UintArray.ets new file mode 100644 index 0000000000000000000000000000000000000000..b595a6647c40689bbd3e2fb104bee6602588bc6e --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/UintArray.ets @@ -0,0 +1,101 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Uint8Array类型和String以及hex如何互相转换 + */ + +// [Start conversion] +import { buffer, util } from '@kit.ArkTS'; + + +// Convert string to byte stream +function stringToUint8Array(str: string) { + console.info('Convert string to byte stream:' + new Uint8Array(buffer.from(str, 'utf-8').buffer)); + return new Uint8Array(buffer.from(str, 'utf-8').buffer); +} + + +// Byte flow into understandable strings +function uint8ArrayToString(array: Uint8Array) { + let textDecoderOptions: util.TextDecoderOptions = { + fatal: false, + ignoreBOM: true + } + let decodeToStringOptions: util.DecodeToStringOptions = { + stream: false + } + let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions); + let retStr = textDecoder.decodeToString(array, decodeToStringOptions); + console.info('Byte flow into understandable strings:' + retStr); + return retStr; +} + + +//Hexadecimal to Uint8Array +function HexStrTouint8Array(data: string): Uint8Array { + console.info('Hexadecimal to Uint8Array:' + new Uint8Array(buffer.from(data, 'hex').buffer)); + return new Uint8Array(buffer.from(data, 'hex').buffer); +} + + +// Uint8Array to hexadecimal +function uint8ArrayToHexStr(data: Uint8Array): string { + let hexString = ''; + let i: number; + for (i = 0; i < data.length; i++) { + let char = ('00' + data[i].toString(16)).slice(-2); + hexString += char; + } + console.info('Uint8Array to hexadecimal:' + hexString); + return hexString; +} + + +let uint8Array: Uint8Array; + + +@Entry +@Component +struct TypeConversion { + build() { + Column({ space: 12 }) { + Button('Convert string to byte stream') + .onClick(() => { + let str = 'hello'; + uint8Array = stringToUint8Array(str); + }) + Button('Byte flow string') + .onClick(() => { + if (uint8Array) { + uint8ArrayToString(uint8Array); + } + }) + Button('Hexadecimal to Uint8Array') + .onClick(() => { + let data = '05160b22'; + HexStrTouint8Array(data); + }) + Button('Uint8Array to hexadecimal') + .onClick(() => { + let uint8Array = new Uint8Array([5, 22, 11, 34]); + uint8ArrayToHexStr(uint8Array); + }) + } + .width('100%') + .justifyContent(FlexAlign.Center) + } +} +// [End conversion] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/UseRecord.ets b/ArkTS/entry/src/main/ets/pages/UseRecord.ets new file mode 100644 index 0000000000000000000000000000000000000000..c1b22571cf77a6dd0499388c940f0fa621a7bf47 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/UseRecord.ets @@ -0,0 +1,102 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用Record + */ + +// [Start use_record] +// Define course types +type Course = 'Math' | 'Chinese' | 'English'; + + +// Define grade types +type Grade = number; + + +// Define student grade record types +type StudentGrades = Record; + + +// Define the type of class grade record, where the key is the student ID and the value is the student's grade record +type ClassGrades = Record; + + +interface StudentCourseGrade { + Math: number, + Chinese: number, + English: number +} + + +let student1: StudentCourseGrade = { + Math: 90, + Chinese: 85, + English: 92 +} +let student2: StudentCourseGrade = { + Math: 78, + Chinese: 82, + English: 85 +} +let student3: StudentCourseGrade = { + Math: 95, + Chinese: 89, + English: 90 +} + + +// Initialize class grades +const classGrades: ClassGrades = { + '001': student1, + '002': student2, + '003': student3 +}; + + +@Entry +@Component +struct Index { + // Obtain the average grade of a student + getAverageGrade(studentId: string, grades: ClassGrades): number | null { + const studentGrades = grades[studentId]; // Obtain corresponding grade data for students + if (!studentGrades) { + console.log(`Student with ID ${studentId} not found.`); + return null; + } + + + const courses = Object.keys(studentGrades) as Course[]; // Course type array + // Calculate the total grade of the course + const total = courses.reduce((sum, course) => sum + studentGrades[course], 0); + return total / courses.length; // Average score + } + + + build() { + Row() { + Column() { + Button('getAverageGrade') + .onClick(() => { + // output: 89 + console.log('student average grade is:', this.getAverageGrade('001', classGrades)); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End use_record] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/module.ets b/ArkTS/entry/src/main/ets/pages/module.ets new file mode 100644 index 0000000000000000000000000000000000000000..a5b2a250ccb8771a80ced9bc3919f7775cead755 --- /dev/null +++ b/ArkTS/entry/src/main/ets/pages/module.ets @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何实现类似Java中的反射方法调用能力 + */ + +// [Start data_table] +export class DataTable { + constructor() { + } + static tagName(){ + return 'data-table' + } +} +// [End data_table] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/utils/ObjectUtil.ts b/ArkTS/entry/src/main/ets/utils/ObjectUtil.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a96d807b1782cb21ee26f6e137de6888c88c0d9 --- /dev/null +++ b/ArkTS/entry/src/main/ets/utils/ObjectUtil.ts @@ -0,0 +1,26 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何判断能否对接口进行插桩或替换 + */ + +// [Start object_util] +export class ObjectUtil { + static ObjectGetOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined{ + return Object.getOwnPropertyDescriptor(o, p) + } +} +// [End object_util] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/utils/TaskPool.txt b/ArkTS/entry/src/main/ets/utils/TaskPool.txt new file mode 100644 index 0000000000000000000000000000000000000000..53139c665b633e080bf8e0a25243550498e35e31 --- /dev/null +++ b/ArkTS/entry/src/main/ets/utils/TaskPool.txt @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将类Java语言的线程模型(内存共享)的实现方式转换成在ArkTS的线程模型下(内存隔离)的实现方式 + */ + +// [Start Task1] +class Task { + static run(args) { + // Do some independent tasks + } +} +let thread = new Thread(() => { + let result = Task.run(args) + // deal with result +}) +// [End Task1] + +// [Start Task2] +class Material { + action(args) { + // Do some independent tasks + } +} +let material = new Material() +let thread = new Thread(() => { + let result = material.action(args) + // deal with result +}) +// [End Task2] + +// [Start Task3] +class Task { + run(args) { + // deal with result + runOnUiThread(() => { + UpdateUI(result) + }) + } +} +let task = new Task() +let thread = new Thread(() => { + let result = task.run(args) + // Processing results +}) +// [End Task3] + +// [Start Task4] +class SdkU3d { + static getInst() { + return SdkMgr.getInst(); + } + getPropStr(str: string) { + return xx; + } +} +let thread = new Thread(() => { + // In the game thread + let sdk = SdkU3d.getInst() + let ret = sdk.getPropStr("xx") +}) +// [End Task4] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/utils/testClass.ts b/ArkTS/entry/src/main/ets/utils/testClass.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0453f88a01181b55769c581737df4f4f612d406 --- /dev/null +++ b/ArkTS/entry/src/main/ets/utils/testClass.ts @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何获取对象的所有方法 + */ + +// [Start test_class] +export class testClass { + public test(): string { + return "ArkUI Web Component"; + } + + + public toString(): void { + console.log('Web Component toString'); + } + + + public FunToString(): void { + console.log('Web Component toString'); + } +} +// [End test_class] \ No newline at end of file diff --git a/ArkTS/harlibrary/.gitignore b/ArkTS/harlibrary/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e2713a2779c5a3e0eb879efe6115455592caeea5 --- /dev/null +++ b/ArkTS/harlibrary/.gitignore @@ -0,0 +1,6 @@ +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/ArkTS/harlibrary/BuildProfile.ets b/ArkTS/harlibrary/BuildProfile.ets new file mode 100644 index 0000000000000000000000000000000000000000..3a501e5ddee8ea6d28961648fc7dd314a5304bd4 --- /dev/null +++ b/ArkTS/harlibrary/BuildProfile.ets @@ -0,0 +1,17 @@ +/** + * Use these variables when you tailor your ArkTS code. They must be of the const type. + */ +export const HAR_VERSION = '1.0.0'; +export const BUILD_MODE_NAME = 'debug'; +export const DEBUG = true; +export const TARGET_NAME = 'default'; + +/** + * BuildProfile Class is used only for compatibility purposes. + */ +export default class BuildProfile { + static readonly HAR_VERSION = HAR_VERSION; + static readonly BUILD_MODE_NAME = BUILD_MODE_NAME; + static readonly DEBUG = DEBUG; + static readonly TARGET_NAME = TARGET_NAME; +} \ No newline at end of file diff --git a/ArkTS/harlibrary/Index.ets b/ArkTS/harlibrary/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..057ebce793aaf5e78a461f756d229134a03d14f9 --- /dev/null +++ b/ArkTS/harlibrary/Index.ets @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS是否支持反射调用类的静态成员函数和实例成员函数 +* FAQ:是否支持模块的动态加载?如何实现 + */ + +// [Start harlibrary_index] +// harlibrary's Index.ets +export { Calc, addHarlibrary } from './src/main/ets/utils/Calc' +// [End harlibrary_index] \ No newline at end of file diff --git a/ArkTS/harlibrary/build-profile.json5 b/ArkTS/harlibrary/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..e6773f9f5d76a66d6d19fddc9c6ddb3f5621d3b1 --- /dev/null +++ b/ArkTS/harlibrary/build-profile.json5 @@ -0,0 +1,31 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": false, + "files": [ + "./obfuscation-rules.txt" + ] + }, + "consumerFiles": [ + "./consumer-rules.txt" + ] + } + }, + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest" + } + ] +} diff --git a/ArkTS/harlibrary/consumer-rules.txt b/ArkTS/harlibrary/consumer-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ArkTS/harlibrary/hvigorfile.ts b/ArkTS/harlibrary/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..42187071482d292588ad40babeda74f7b8d97a23 --- /dev/null +++ b/ArkTS/harlibrary/hvigorfile.ts @@ -0,0 +1,6 @@ +import { harTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/ArkTS/harlibrary/obfuscation-rules.txt b/ArkTS/harlibrary/obfuscation-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..272efb6ca3f240859091bbbfc7c5802d52793b0b --- /dev/null +++ b/ArkTS/harlibrary/obfuscation-rules.txt @@ -0,0 +1,23 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope + +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/ArkTS/harlibrary/oh-package.json5 b/ArkTS/harlibrary/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..306813f32ba14f1c0c693bc4355709c3a1570a41 --- /dev/null +++ b/ArkTS/harlibrary/oh-package.json5 @@ -0,0 +1,9 @@ +{ + "name": "harlibrary", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "Index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": {} +} diff --git a/ArkTS/harlibrary/src/main/ets/components/MainPage.ets b/ArkTS/harlibrary/src/main/ets/components/MainPage.ets new file mode 100644 index 0000000000000000000000000000000000000000..9de5eb33fe973c00e1ddc28c9f079ace6d473711 --- /dev/null +++ b/ArkTS/harlibrary/src/main/ets/components/MainPage.ets @@ -0,0 +1,19 @@ +@Component +export struct MainPage { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .width('100%') + } + .height('100%') + } +} diff --git a/ArkTS/harlibrary/src/main/ets/utils/Calc.ets b/ArkTS/harlibrary/src/main/ets/utils/Calc.ets new file mode 100644 index 0000000000000000000000000000000000000000..981597caacd094a1a16ad70ba260cd3eef1c0b52 --- /dev/null +++ b/ArkTS/harlibrary/src/main/ets/utils/Calc.ets @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS是否支持反射调用类的静态成员函数和实例成员函数 +* FAQ:是否支持模块的动态加载?如何实现 + */ + +// [Start harlibrary1] +// harlibrary's src/main/ets/utils/Calc.ets +export class Calc { + public static staticAdd(a:number, b:number):number { + let c = a + b; + console.log('DynamicImport I am harlibrary in staticAdd, %d + %d = %d', a, b, c); + return c; + } + public instanceAdd(a:number, b:number):number { + let c = a + b; + console.log('DynamicImport I am harlibrary in instanceAdd, %d + %d = %d', a, b, c); + return c; + } +} +export function addHarlibrary(a:number, b:number):number { + let c = a + b; + console.log('DynamicImport I am harlibrary in addHarlibrary, %d + %d = %d', a, b, c); + return c; +} +// [End harlibrary1] \ No newline at end of file diff --git a/ArkTS/harlibrary/src/main/module.json5 b/ArkTS/harlibrary/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..984417acd7968d8e2487416a3f958a28f17cb22b --- /dev/null +++ b/ArkTS/harlibrary/src/main/module.json5 @@ -0,0 +1,11 @@ +{ + "module": { + "name": "harlibrary", + "type": "har", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ] + } +} diff --git a/ArkTS/harlibrary/src/main/resources/base/element/float.json b/ArkTS/harlibrary/src/main/resources/base/element/float.json new file mode 100644 index 0000000000000000000000000000000000000000..33ea22304f9b1485b5f22d811023701b5d4e35b6 --- /dev/null +++ b/ArkTS/harlibrary/src/main/resources/base/element/float.json @@ -0,0 +1,8 @@ +{ + "float": [ + { + "name": "page_text_font_size", + "value": "50fp" + } + ] +} diff --git a/ArkTS/harlibrary/src/main/resources/base/element/string.json b/ArkTS/harlibrary/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f51a9c8461a55f6312ef950344e3145b7f82d607 --- /dev/null +++ b/ArkTS/harlibrary/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "page_show", + "value": "page from package" + } + ] +} diff --git a/ArkTS/harlibrary/src/ohosTest/ets/test/Ability.test.ets b/ArkTS/harlibrary/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..85c78f67579d6e31b5f5aeea463e216b9b141048 --- /dev/null +++ b/ArkTS/harlibrary/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,35 @@ +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function abilityTest() { + describe('ActsAbilityTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }) + }) +} \ No newline at end of file diff --git a/ArkTS/harlibrary/src/ohosTest/ets/test/List.test.ets b/ArkTS/harlibrary/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..794c7dc4ed66bd98fa3865e07922906e2fcef545 --- /dev/null +++ b/ArkTS/harlibrary/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,5 @@ +import abilityTest from './Ability.test'; + +export default function testsuite() { + abilityTest(); +} \ No newline at end of file diff --git a/ArkTS/harlibrary/src/ohosTest/module.json5 b/ArkTS/harlibrary/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..8e718f10d8d2082758b9a0127b62a698a4c6aeef --- /dev/null +++ b/ArkTS/harlibrary/src/ohosTest/module.json5 @@ -0,0 +1,13 @@ +{ + "module": { + "name": "harlibrary_test", + "type": "feature", + "deviceTypes": [ + "default", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false + } +} diff --git a/ArkTS/harlibrary/src/test/List.test.ets b/ArkTS/harlibrary/src/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..bb5b5c3731e283dd507c847560ee59bde477bbc7 --- /dev/null +++ b/ArkTS/harlibrary/src/test/List.test.ets @@ -0,0 +1,5 @@ +import localUnitTest from './LocalUnit.test'; + +export default function testsuite() { + localUnitTest(); +} \ No newline at end of file diff --git a/ArkTS/harlibrary/src/test/LocalUnit.test.ets b/ArkTS/harlibrary/src/test/LocalUnit.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..165fc1615ee8618b4cb6a622f144a9a707eee99f --- /dev/null +++ b/ArkTS/harlibrary/src/test/LocalUnit.test.ets @@ -0,0 +1,33 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; + +export default function localUnitTest() { + describe('localUnitTest', () => { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(() => { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }); + beforeEach(() => { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }); + afterEach(() => { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }); + afterAll(() => { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }); + it('assertContain', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + let a = 'abc'; + let b = 'b'; + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b); + expect(a).assertEqual(a); + }); + }); +} \ No newline at end of file diff --git a/ArkTS/oh-package-lock.json5 b/ArkTS/oh-package-lock.json5 index c6f99f5c73b06c5fdef7ec6f491b74b7befebe2e..48c26157079236edb1c763c45bfc0a0be26c92eb 100644 --- a/ArkTS/oh-package-lock.json5 +++ b/ArkTS/oh-package-lock.json5 @@ -6,7 +6,9 @@ "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "specifiers": { "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0", - "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21" + "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21", + "class-transformer@^0.5.1": "class-transformer@0.5.1", + "reflect-metadata@0.1.13": "reflect-metadata@0.1.13" }, "packages": { "@ohos/hamock@1.0.0": { @@ -22,6 +24,22 @@ "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==", "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.21.har", "registryType": "ohpm" + }, + "class-transformer@0.5.1": { + "name": "class-transformer", + "version": "0.5.1", + "integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==", + "resolved": "https://ohpm.openharmony.cn/ohpm/class-transformer/-/class-transformer-0.5.1.tgz", + "shasum": "24147d5dffd2a6cea930a3250a677addf96ab336", + "registryType": "ohpm" + }, + "reflect-metadata@0.1.13": { + "name": "reflect-metadata", + "version": "0.1.13", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==", + "resolved": "https://ohpm.openharmony.cn/ohpm/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "shasum": "67ae3ca57c972a2aa1642b10fe363fe32d49dc08", + "registryType": "ohpm" } } } \ No newline at end of file diff --git a/ArkTS/oh-package.json5 b/ArkTS/oh-package.json5 index 75e4e229db0f608fc3d9471c8819d0e52fb403c5..0ea39a3c9c483d34ab828c7fb88dbef29bc45c0c 100644 --- a/ArkTS/oh-package.json5 +++ b/ArkTS/oh-package.json5 @@ -2,9 +2,12 @@ "modelVersion": "5.0.4", "description": "Please describe the basic information.", "dependencies": { + "reflect-metadata": "0.1.13", + "class-transformer": "^0.5.1" }, "devDependencies": { "@ohos/hypium": "1.0.21", "@ohos/hamock": "1.0.0" - } -} + }, + "dynamicDependencies": {} +} \ No newline at end of file diff --git a/Ipc/oh-package-lock.json5 b/Ipc/oh-package-lock.json5 new file mode 100644 index 0000000000000000000000000000000000000000..7fcf818273347b97063c0c0a151bb14770ca1c79 --- /dev/null +++ b/Ipc/oh-package-lock.json5 @@ -0,0 +1,27 @@ +{ + "meta": { + "stableOrder": true + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0", + "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21" + }, + "packages": { + "@ohos/hamock@1.0.0": { + "name": "@ohos/hamock", + "version": "1.0.0", + "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har", + "registryType": "ohpm" + }, + "@ohos/hypium@1.0.21": { + "name": "@ohos/hypium", + "version": "1.0.21", + "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==", + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.21.har", + "registryType": "ohpm" + } + } +} \ No newline at end of file