Is there a command to Move Fields from an internal structure to fields of a data reference from the same type?

92 views Asked by At

I have the following code in ABAP, which I would like to simplify. I have a CDS View of type Z_I_CAR and an internal structure of type ZCAR and I need to make a data reference to the CDS View in order to hand it over to a BOPF Object.

It´s just an example and my structure has more than 60 fields. Is it possible to assign the corresponding fields of an internal structure to a data reference with a single command?

DATA: lr_car TYPE REF TO Z_I_CAR, 
      ls_car TYPE ZCAR. 

CREATE DATA lr_car. 

lr_car->model = ls_car-model. 
lr_car->weight = ls_car-weight. 
lr_car->height = ls_car-height. 
..
..      

Thank you and best regards Patrick

3

There are 3 answers

0
mkysoft On

I didn't see any command for this yet. You can use your own implementation like below:

REPORT zmky_move_oop.

DATA: BEGIN OF ls_itab,
        field1 TYPE i,
        field2 TYPE i,
        field3 TYPE i,
      END OF ls_itab.

CLASS zcl_test DEFINITION.
  PUBLIC SECTION.
    DATA: field1 TYPE i,
          field2 TYPE i.
ENDCLASS.

CLASS zcl_test IMPLEMENTATION.
ENDCLASS.

DATA lo_test TYPE REF TO zcl_test.
CREATE OBJECT lo_test.

DATA: lo_struct TYPE REF TO cl_abap_structdescr,
      lt_comp   TYPE abap_component_tab,
      ls_comp   TYPE abap_componentdescr.

FIELD-SYMBOLS <fs_src> TYPE any.
FIELD-SYMBOLS <fs_trg> TYPE any.

lo_struct ?= cl_abap_typedescr=>describe_by_data( ls_itab ).
lt_comp = lo_struct->get_components( ).

LOOP AT lt_comp INTO ls_comp.
  ASSIGN lo_test->(ls_comp-name) TO <fs_trg>.
  CHECK sy-subrc IS INITIAL.
  DATA(lv_name) = 'ls_itab-' && ls_comp-name.
  ASSIGN (lv_name) TO <fs_src>.
  <fs_trg> = <fs_src>.
ENDLOOP.
0
Michael Koval On

Yes, you can use move-corresponding on a dereferenced reference variable.

TYPES: BEGIN OF test1,
         a TYPE char1,
         b TYPE numc1,
         c TYPE i,
         d TYPE xstring,
       END OF test1.

TYPES: BEGIN OF test2,
         a TYPE char1,
         b TYPE numc1,
         e TYPE i,
         f TYPE xstring,
       END OF test2.

DATA x TYPE test1.
DATA y TYPE REF TO test2.

x = VALUE #( a = 'A' b = '1' c = 9 d = '41' ).
CREATE DATA y.

MOVE-CORRESPONDING x TO y->*.

ASSERT x-a = y->a. "true
ASSERT x-b = y->b. "true
0
Schesam On
lr_car->* = CORRESPONDING #( ls_car ).

Should also do the trick