ABAP动态编程---动态创建数据类型

代码演示了如何创建structure类型,并以其为行类型创建内表.
DATA: lrf_result_descr TYPE REF TO cl_abap_structdescr,
      lt_comp          TYPE cl_abap_structdescr=>component_table,
      l_comp           LIKE LINE OF lt_comp.

DATA: lrf_res_tabledescr TYPE REF TO cl_abap_tabledescr.

DATA: lrf_datadescr TYPE REF TO cl_abap_datadescr.

  lrf_datadescr     ?= cl_abap_datadescr=>describe_by_name( 'WERKS_D' ).
  l_comp-name       = 'WERKS'.
  l_comp-type       = lrf_datadescr.
  l_comp-as_include = abap_false.
  l_comp-suffix     = ''.
  APPEND l_comp TO lt_comp.

  lrf_datadescr     ?= cl_abap_datadescr=>describe_by_name( 'ARBPL' ).
  l_comp-name       = 'ARBPL'.
  l_comp-type       = lrf_datadescr.
  l_comp-as_include = abap_false.
  l_comp-suffix     = ''.
  APPEND l_comp TO lt_comp.

  lrf_result_descr   = cl_abap_structdescr=>create( lt_comp ).
  lrf_res_tabledescr = cl_abap_tabledescr=>create( lrf_result_descr  ).

  DATA: lw_result TYPE REF TO data,
        lt_result TYPE REF TO data.

  CREATE DATA lw_result TYPE HANDLE lrf_result_descr.
  CREATE DATA lt_result TYPE HANDLE lrf_res_tabledescr.

  FIELD-SYMBOLS: <lt_res> TYPE STANDARD TABLE,
                 <lw_res> TYPE ANY,
                 <lw_any> TYPE ANY.

  ASSIGN lt_result->* TO <lt_res>.
  ASSIGN lw_result->* TO <lw_res>.

  ASSIGN COMPONENT 'WERKS' OF STRUCTURE <lw_res>
    TO <lw_any>.
  <lw_any> = '0000000'.
  APPEND <lw_res> TO <lt_res>.

  ASSIGN COMPONENT 'WERKS' OF STRUCTURE <lw_res>
  TO <lw_any>.
  <lw_any> = '9999999'.
  APPEND <lw_res> TO <lt_res>.

  LOOP AT <lt_res> INTO <lw_res>.
    ASSIGN COMPONENT 'WERKS' OF STRUCTURE <lw_res>
      TO <lw_any>.

    WRITE: / <lw_any>.

  ENDLOOP.

动态编程是运行时才开始创建类型, 对程序的运行有影响,不建议经常使用.但在一些像比较通用功能的实现中, 如查询ABAP Dictionary中的透明表的数据内容,就可以采用动态编程实现.


你可能感兴趣的:(编程)