ABAP语言的动态编程(3) - data reference 对象

如果数据对象的类型在运行时才知道,就需要用到 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 statement CREATE DATAuses the addition HANDLEto create a data object whose data type is described by an  RTTS  type description object. For handle, a reference variable of the static type of class CL_ABAP_DATADESCRor 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 name

data(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> ).

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值