ABAP Keyword Documentation →  ABAP − Reference →  Creating Objects and Values →  CREATE DATA →  CREATE DATA - REF TO → 

Creating Reference Variables

This example demonstrates how to create a reference variable.

Source Code

REPORT demo_create_reference.

INTERFACE intf.
  CONSTANTS attr TYPE string VALUE `Interface constant`.
ENDINTERFACE.

CLASS cls DEFINITION.
  PUBLIC SECTION.
    INTERFACES intf.
ENDCLASS.

CLASS demo DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS main.
ENDCLASS.

CLASS demo IMPLEMENTATION.
  METHOD main.
    DATA intf_name TYPE string.
    DATA cls_name  TYPE string.
    DATA dref TYPE REF TO data.

    FIELD-SYMBOLS <ref>  TYPE any.
    FIELD-SYMBOLS <attr> TYPE any.

    intf_name = '\PROGRAM=DEMO_CREATE_REFERENCE\INTERFACE=INTF'.
    CREATE DATA dref TYPE REF TO (intf_name).
    ASSIGN dref->* TO <ref>.

    cls_name = '\PROGRAM=DEMO_CREATE_REFERENCE\CLASS=CLS'.
    CREATE OBJECT <ref> TYPE (cls_name).

    ASSIGN ('<REF>->ATTR') TO <attr>.
    cl_demo_output=>display_data( <attr> ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  demo=>main( ).

Description

Dynamic generation of an interface reference variable. The absolute type name is used for the name of the local interface.

The reference variable is assigned to a field symbol <ref> by means of dereferencing. According to the general typing rules, the field symbol must either be typed completely generically or typed with reference to the interface intf.

The dynamically generated reference variable is used to create and address an object of a class. As this field symbol is completely generic, only the display variant of the dynamic ASSIGN (and not a special Dynamic Access) can be used to access the interface attribute.