2008年(49)
分类:
2008-06-19 17:51:45
REPORT z_temp_demo8.
DATA: BEGIN OF itab OCCURS 0,
num(10),
name(20),
age TYPE i,
sex(6),
END OF itab.
DATA: type_ref TYPE REF TO cl_abap_typedescr,
struct_ref TYPE REF TO cl_abap_structdescr,
struct_info TYPE LINE OF abap_compdescr_tab,
field_column TYPE i,
tab_lines TYPE i.
FIELD-SYMBOLS
itab-num = '1'.
itab-name = 'Lee'.
itab-age = 23.
itab-sex = 'male'.
APPEND itab.
itab-num = '2'.
itab-name = 'Eason'.
itab-age = 35.
itab-sex = 'male'.
APPEND itab.
itab-num = '3'.
itab-name = 'Mary'.
itab-age = 21.
itab-sex = 'female'.
APPEND itab.
CALL METHOD cl_abap_typedescr=>describe_by_data
EXPORTING
p_data = itab
RECEIVING
p_descr_ref = type_ref.
struct_ref ?= type_ref.
DESCRIBE TABLE struct_ref->components LINES tab_lines.
field_column = -1.
LOOP AT struct_ref->components INTO struct_info.
IF struct_info-name = 'AGE'.
field_column = sy-tabix.
ENDIF.
ENDLOOP.
IF field_column = -1.
write: / 'No field named ''AGE'''.
ELSE.
LOOP AT itab.
ASSIGN COMPONENT field_column OF STRUCTURE itab TO
write: /
ENDLOOP.
ENDIF.
关于程序的一点说明:
1.cl_abap_typedescr(当然用cl_abap_structdescr也可以)的静态方法describe_by_data ,返回值是一个cl_abap_typedescr类型的接口。其实这个静态方法是创建了一个对象,这个对象一定是实现了cl_abap_typedescr接口的,而且方法把这个接口暴露在外,通过它来抓住这个对象。如果传入的是结构体,那么对象还会实现cl_abap_structdescr接口,其中有components属性,有结构的字段信息。如果传入的是基本数据,那么则是cl_abap_datadescr接口被实现。
2. 通过 ASSIGN COMPONENT field_column OF STRUCTURE itab TO
meiok12008-07-14 22:02:21
好,从哪儿鼓捣了这么多多class,挺好用.
补充个说明二的例子:
输出结构体中所有字段的值.
1.语法要点ASSIGN COMPONENT sy-index
REPORT z_assigncomponent.
DATA spfli_wa TYPE spfli.
FIELD-SYMBOLS: