如果数据对象的类型在运行时才知道,就需要用到 data reference 对象。
Data references can point to any data objects or to their parts (components, rows of internal tables, or sections specified by offsets and lengths)
也就是说 data reference 对象其实就是指针,储存的是引用对象的地址。和 field symbol 不同的是,data reference 对象不能直接进行赋值,需要通过 ->* 符号 (被称作解引用操作符 , dereferencing operator)。
我们先看一个例子,这个例子没有什么实际意义,主要作用就是演示语法:
data lr_num type ref to i.
create data lr_num.
lr_num->* = 2.write: / lr_num->*.
比较有用的用法就是通过创建一个参照 data 的数据对象,然后在程序中确定数据类型。
data dref type ref to data.
在 ABAP 中,data 表示泛型的数据类型 (generic data type)。因为参照 data ,没有确定的数据类型,所以在程序中需要确定数据类型,有两种方法。第一种方法如下:
data dref type ref to data.
field-symbols <line> type any.create data dref type mara.
assign dref->* to <line>.select * from mara into table @data(it_mara) up to 10 rows.
loop at it_mara assigning <line>.assign component 'MATNR' of structure <line> to field-symbol(<fld>).write: / <fld>.
endloop.
声明一个参照到 data 的 data reference object 之后,在 create data 语句之中通过 type 限定符将 dref 的数据类型设置为 mara 表类型。
第二种方法,通过 handle 限定符,支持根据 RTTS 类型来确定 data reference 的类型
The statementCREATE DATA
uses the additionHANDLE
to create a data object whose data type is described by an RTTS type description object. Forhandle
, a reference variable of the static type of classCL_ABAP_DATADESCR
or its subclasses that points to a type description object must be specified.
data dref type ref to data.
field-symbols <line> type any.parameters tab_name type tabname. " table namedata(struct_descr) = cl_abap_structdescr=>describe_by_name( tab_name ).
data(table_descr) = cl_abap_tabledescr=>create( p_line_type = cast #( struct_descr ) ).data table_dref type ref to data.
create data table_dref type handle table_descr.field-symbols <table> type any table.
assign table_dref->* to <table>.select * from (tab_name) up to 10 rows into corresponding fields of table <table>.cl_demo_output=>display( <table> ).