ABAP – How to declare a variable dynamically

SAPIn case you need to create a variable dynamically during runtime with different type, length or precision, you can use the following piece of code to achieve the same – the variable is created dynamically based on given type, length and number of decimals.

DATA: lr_data TYPE REF TO data,
      l_numchar(8) TYPE c.

FIELD-SYMBOLS:
  <fs_data> TYPE ANY.

CLASS lcl_utils DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS:
      create_variable
        IMPORTING
          i_type TYPE c
          i_length TYPE i
          i_decimals TYPE i
        RETURNING value(r_data) TYPE REF TO data.
ENDCLASS.

CLASS lcl_utils IMPLEMENTATION.
  METHOD create_variable.
    DATA:
      lr_var_description TYPE REF TO cl_abap_elemdescr.
 
    CASE i_type.
      WHEN 'P'.
        TRY.
            CALL METHOD cl_abap_elemdescr=>get_p
              EXPORTING
                p_length = i_length
                p_decimals = i_decimals
              RECEIVING
                p_result = lr_var_description.
          CATCH cx_parameter_invalid_range .
*             ... some error handling
        ENDTRY.
      WHEN 'I'.
        CALL METHOD cl_abap_elemdescr=>get_i
          RECEIVING
            p_result = lr_var_description.
      WHEN 'C'.
        TRY.
            CALL METHOD cl_abap_elemdescr=>get_c
              EXPORTING
                p_length = i_length
              RECEIVING
                p_result = lr_var_description.
          CATCH cx_parameter_invalid_range .
*           ... some error handling
        ENDTRY.
    ENDCASE.

    CREATE DATA r_data TYPE HANDLE lr_var_description.    
  ENDMETHOD. "create_variable
ENDCLASS. "lcl_utils IMPLEMENTATION

START-OF-SELECTION.
  lr_data = lcl_utils=>create_variable(
    i_type = 'P'
    i_length = '8'
    i_decimals = '2'
  ).
  CHECK lr_data IS BOUND.
  
  l_numchar = '4.5689'.
  
  ASSIGN lr_data->* TO <fs_data>.
  <fs_data> = l_numchar.
  WRITE <fs_data>.

Leave a Reply