Creating a variable with dynamic variable type in SAP ABAP

You can use RTTS (Run Time Type Services) related API to create a standard table like RANGE which has components like LOW, HIGH, SIGN, and OPTION. This technique allows you to dynamically create variables with types determined at runtime.

Variable Declarations

First, declare the necessary variables and references for dynamic type creation ?

DATA:
  rr_data             TYPE REF TO data,
  rt_range_string     TYPE RANGE OF string,
  rs_range_string     LIKE LINE OF rt_range_string,
  rt_component        TYPE abap_component_tab,
  rs_component        TYPE LINE OF abap_component_tab,
  rt_range_components TYPE abap_component_tab,
  ro_struc_descr      TYPE REF TO cl_abap_structdescr,
  ro_table_descr      TYPE REF TO cl_abap_tabledescr,
  ro_data_descr       TYPE REF TO cl_abap_datadescr.

Field Symbols

Define field symbols to work with the dynamically created variables ?

FIELD-SYMBOLS:
  <var_value>      TYPE any,
  <rt_range_type>  TYPE STANDARD TABLE,  " Range table
  <rs_range_type>  TYPE any.

DATA(var_type) = 'BU_PARTNER'.

Example

Here's how to dynamically create a range table with variable type components ?

" Create data reference with dynamic type
CREATE DATA rr_data TYPE (var_type).

" Get structure description of range string
ro_struc_descr ?= cl_abap_structdescr=>describe_by_data( p_data = rs_range_string ).
rt_component = ro_struc_descr->get_components( ).

" Get data description for the variable type
ro_data_descr ?= cl_abap_elemdescr=>describe_by_name( var_type ).

" Build range components dynamically
rt_range_components = VALUE #( FOR comp IN rt_component (
  name = comp-name
  type = COND #(
    WHEN comp-name EQ 'SIGN'
    OR comp-name EQ 'OPTION'
    THEN comp-type
    ELSE ro_data_descr )
) ).

" Create structure and table descriptions
ro_struc_descr ?= cl_abap_structdescr=>create( rt_range_components ).
ro_table_descr ?= cl_abap_tabledescr=>create( ro_struc_descr ).

" Create the dynamic range table
CREATE DATA rr_data TYPE HANDLE ro_table_descr.
ASSIGN rr_data->* TO <rt_range_type>.

" Create and populate a line of the range table
CREATE DATA rr_data LIKE LINE OF <rt_range_type>.
ASSIGN rr_data->* TO <rs_range_type>.

" Assign values to range components
ASSIGN COMPONENT 'SIGN' OF STRUCTURE <rs_range_type> TO <var_value>.
<var_value> = 'I'.

ASSIGN COMPONENT 'OPTION' OF STRUCTURE <rs_range_type> TO <var_value>.
<var_value> = 'EQ'.

ASSIGN COMPONENT 'LOW' OF STRUCTURE <rs_range_type> TO <var_value>.
<var_value> = 'X1'.

ASSIGN COMPONENT 'HIGH' OF STRUCTURE <rs_range_type> TO <var_value>.
<var_value> = 'X2'.

Conclusion

This approach demonstrates how to use RTTS to create dynamic range tables with variable types determined at runtime, providing flexibility in ABAP programming when dealing with different data types.

Updated on: 2026-03-13T18:01:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements