Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing Internal Data →  Attributes of Data Objects →  RTTS - Run Time Type Services 

Ascertaining Object Types

This example demonstrates how the dynamic type of objects is determined at runtime.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA: oref1 TYPE REF TO object,
          oref2 TYPE REF TO object.

    DATA: descr_ref1 TYPE REF TO cl_abap_typedescr,
          descr_ref2 TYPE REF TO cl_abap_typedescr,
          mess       TYPE string.

    TRY.
        CREATE OBJECT: oref1 TYPE (otype1),
                       oref2 TYPE (otype2).

      CATCH cx_sy_create_object_error.
        MESSAGE 'Create object error!' TYPE 'I' DISPLAY LIKE 'E'.
        LEAVE PROGRAM.

      CATCH cx_root.
        MESSAGE 'Other error!' TYPE 'I' DISPLAY LIKE 'E'.
        LEAVE PROGRAM.

    ENDTRY.

    descr_ref1 = cl_abap_typedescr=>describe_by_object_ref( oref1 ).
    descr_ref2 = cl_abap_typedescr=>describe_by_object_ref( oref2 ).

    TRY.
        IF descr_ref1 <> descr_ref2.
          RAISE EXCEPTION TYPE conv_exc.
        ELSE.
          oref1 = oref2.
        ENDIF.

      CATCH conv_exc.
        mess =  `Assignment from type `   &&
                descr_ref2->absolute_name &&
                ` to `                   &&
                descr_ref1->absolute_name &&
                ` not allowed!`.
        MESSAGE mess TYPE 'I' DISPLAY LIKE 'E'.
    ENDTRY.

Description

This example is the counterpart for object types of the example for data types. Here the dynamic type of reference variables is determined, that is, the absolute type name of the class of the object being referenced.