• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# \@Type装饰器:标记类属性的类型
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @zzq212050299-->
5<!--Designer: @s10021109-->
6<!--Tester: @TerryTsao-->
7<!--Adviser: @zhang_yixin13-->
8
9为了实现序列化类时不丢失属性的复杂类型,开发者可以使用\@Type装饰器装饰类属性。
10
11\@Type的目的是标记类属性,配合PersistenceV2使用,防止序列化时类丢失。在阅读本文档前,建议提前阅读:[PersistenceV2](./arkts-new-persistencev2.md)。
12
13>**说明:**
14>
15> \@Type从API version 12开始支持。
16>
17> 从API version 12开始,该装饰器支持在原子化服务中使用。
18
19## 概述
20
21\@Type标记类属性,使得类属性序列化时不丢失类型信息,便于类的反序列化。
22
23## 装饰器说明
24
25| \@Type装饰器 | 说明 |
26| ------------------- | ------------------------------------------------------------ |
27| 装饰器参数 | type:类型。 |
28| 可装饰的类型 | Object class以及Array、Date、Map、Set等内嵌类型。 |
29
30## 使用限制
31
321. 只能用在[\@ObservedV2](./arkts-new-observedV2-and-trace.md)装饰的类中,不能用在自定义组件中。
33
34    ```ts
35    class Sample {
36      data: number = 0;
37    }
38    @ObservedV2
39    class Info {
40      @Type(Sample)
41      @Trace sample: Sample = new Sample(); // 正确用法
42    }
43    @Observed
44    class Info2 {
45      @Type(Sample)
46      sample: Sample = new Sample(); // 错误用法,不能用在@Observed装饰的类中,编译时报错
47    }
48    @ComponentV2
49    struct Index {
50      @Type(Sample)
51      sample: Sample = new Sample(); // 错误用法,不能用在自定义组件中
52      build() {
53      }
54    }
55    ```
56
572. 不支持collections.Setcollections.Map等类型。
58
593. 不支持非buildin类型。如PixelMap、NativePointer、ArrayList等Native类型。
60
614. 不支持简单类型。如string、number、boolean等。
62
635. 不支持构造函数含参的类。
64
65## 使用场景
66
67### 持久化数据
68
69```ts
70import { PersistenceV2, Type } from '@kit.ArkUI';
71
72@ObservedV2
73class SampleChild {
74  @Trace childNumber: number = 1;
75}
76
77@ObservedV2
78class Sample {
79  // 对于复杂对象需要@Type修饰,确保反序列化成功,去掉@Type会反序列化值失败。
80  @Type(SampleChild)
81  // 对于没有初值的类属性,经过@Type修饰后,需要手动保存,否则持久化失败。
82  // 无法使用@Type修饰的类属性,必须要有初值才能持久化。
83  @Trace sampleChild?: SampleChild = undefined;
84}
85
86@Entry
87@ComponentV2
88struct TestCase {
89  @Local sample: Sample = PersistenceV2.connect(Sample, () => new Sample)!;
90
91  build() {
92    Column() {
93      Text('childNumber value:' + this.sample.sampleChild?.childNumber)
94        .onClick(() => {
95          this.sample.sampleChild = new SampleChild();
96          this.sample.sampleChild.childNumber = 2;
97          PersistenceV2.save(Sample);
98        })
99        .fontSize(30)
100    }
101  }
102}
103```
104