SAP Tutorials Blog


 


"Performing casts on arguments and creating a reference variable that has the

"static type as specified as a result.


"Declaring data reference variables

DATA ref_i TYPE REF TO i.

DATA ref_gen TYPE REF TO data. "Generic type


"Creating an anonymous data object

ref_i = NEW #( 789 ).


"Upcast

"Static type of the target is less specific than or the same as the static

"type of the source

ref_gen = ref_i.

"The CAST operator can also be specified for upcasts. In this case, it can but

"need not be specified.

ref_gen = CAST #( ref_i ).


"Downcast

"Static type of the target is more specific than the static type of the source

"A check must be made at runtime before the assignment is done. If you indeed

"want to trigger such a downcast, you must do it explicitly in your code, for

"example, using the CAST operator (older operator: ?=).


"A syntax error occurs for the first statement. An explicit casting is required.

"ref_i = ref_gen.

ref_i = CAST #( ref_gen ).


"Like a data reference variable, the expressions can be followed by the

"dereferencing operator

ref_gen = NEW string( `hi` ).

CAST string( ref_gen )->* = `abap`.

DATA(str) = CAST string( ref_gen )->*.


"In case of static structured types, you can use the object component

"selector (->).

ref_gen = NEW zdemo_abap_carr( ).

CAST zdemo_abap_carr( ref_gen )->carrid = 'XY'.

DATA(comp) = CAST zdemo_abap_carr( ref_gen )->carrid.

"Dynamic specifications are possible.

CAST zdemo_abap_carr( ref_gen )->('CARRID') = 'ZZ'.

DATA(dyncomp) = |{ CAST zdemo_abap_carr( ref_gen )->('CARRID') }|.


"In the context of RTTS (see the cheat sheet about dynamic programming),

"helper variables are often required to perform a downcast of a type description

"object to a specialized class. The following examples, show how such helper

"variables can be reduced by using statements with CAST.

"Getting component information

DATA st TYPE zdemo_abap_carr.

DATA(components) = CAST cl_abap_structdescr(

    cl_abap_typedescr=>describe_by_data( st ) )->components.


"A constructor expression as above instead of, for example, using helper variables

"and the older ?= operator.

DATA ref_struc_type TYPE REF TO cl_abap_structdescr.

DATA comps TYPE abap_compdescr_tab.

ref_struc_type ?= cl_abap_typedescr=>describe_by_data( st ).

comps = ref_struc_type->components.


"Getting method information

DATA(methods) = CAST cl_abap_objectdescr(

    cl_abap_objectdescr=>describe_by_name( 'ZCL_DEMO_ABAP_OBJECTS' ) )->methods.


Serkan AKKAVAK

Computer Engineer BSc

SAP Department Manager

Contact : serkurumsal@yandex.com