Dynamic Type Investigation - kazumov/abap GitHub Wiki

Source: https://github.com/kazumov/abap/blob/master/examples/dynamic-table-type.abap

Problem

The internal table moves through methods of classes without reference to its data type. After the passing into the class method, we should perform some additional actions to define the data type of the internal table, retrieved as a method argument.

The Main Module

types: begin of rep,                    " the type definition
       " ... 
       end of rep.
       
data: w_rep type rep,
      t_rep type table of rep.          " the table definition
data: r_pr type ref to processor.
start-of-selection.

  create object r_pr.
  r_pr->work( itab = t_rep ).           " we use internal table as an argument for
                                        " the class instance initialization

The Class Processor

class processor definition.             " inside the definition of the class 'processor',
  public section.
    methods work
      importing itab type index table.  " internal table defined as a generic table
endclass.
*--------------------------------------
class processor implementation.
  method work.                          " inside the class method...
    data r_w type ref to worker.        " 
    create object r_w.
    field-symbols: <t> type any table.  " ... we have no idea what type of the internal table we got exactly
    assign itab to <t>.                 " but we can wrap it inside field symbol...
    r_w->do( some_tab = <t> ).          " ... and use it as an argument of another class instance initialization
  endmethod.
endclass.
*---------------------------------------
class worker definition.                " inside the definition of the class 'worker',
  public section.
    methods do
      importing some_tab type index table. " internal table defined as a generic index table.
endclass.

Inside the class 'worker' we can not use some_tab directly because we have no idea about the table internal structure/type.

Solution

class worker implementation.
  method do.
    " ...
    data: r_des      type ref to cl_abap_structdescr,
          r_some_tab type ref to data,
          t_comp     type abap_component_tab.
    field-symbols: <f_some_tab> type any.
    try.
        create data r_some_tab like line of some_tab. " we should use 'create data ...' 
        assign r_some_tab->* to <f_some_tab>.         " and wrap the pointer in field-symbol

        r_des ?= cl_abap_typedescr=>describe_by_data( <f_some_tab> ). " for use it as a data
        t_comp = r_des->get_components( ).                            " and reach components of the internal table type
        " ...
    endtry.
  endmethod.
endclass.

Data flow

stage:         main           --->  class processor   --->      class worker
data:  itab type table of rep ---> <t> type any table ---> some_tab type index table
⚠️ **GitHub.com Fallback** ⚠️