Thursday, March 26, 2009

Get the components of an internal table dynamically

Sometimes you would want to go through the structure of an internal table in the program without know what the table is based on. Using RTTS (Run Time Type Services) one can find out the definition of any data. The following code will get the components of internal table ITAB. The object of referring class CL_ABAP_STRUCTDESCR will have internal table attribute COMPONENTS that contains all the fields.

DATA:
  l_o_tabledescr TYPE REF TO cl_abap_tabledescr,
  l_o_structdescr TYPE REF TO cl_abap_structdescr,
  l_s_abap_compdescr_tab TYPE abap_compdescr.
FIELD-SYMBOLS:
  <l_fs_field1> TYPE ANY.
l_o_tabledescr ?= cl_abap_tabledescr=>describe_by_data( p_data = itab ).
l_o_structdescr ?= l_o_tabledescr->get_table_line_type( ).
WHILE sy-subrc IS INITIAL.
  ASSIGN COMPONENT sy-index OF STRUCTURE itab TO <l_fs_field1>.
* Get field name
  READ TABLE l_o_structdescr->components INDEX sy-index INTO l_s_abap_compdescr_tab.
ENDWHILE.

No comments: