将一个结构的值分配给ABAP中的动态结构

Assigning values from one structure to a dynamic structure in ABAP

我有两种结构:一种是静态的,一种是动态的。静态结构有四个字段,名称为A B C D。动态结构有两个字段,例如A1和B1,它们与A和B的类型相同,但名称不同。如何将静态结构 A 和 B 中的值分配给 A1 和 B2。问题是:我在运行之前不知道我的 A1 和 B1 是叫 A1 还是 A2 等

感谢您的帮助

如果您的 ABAP 版本超过 7.5。您可以使用 CL_ABAP_CORRESPONDING

types:
begin of test_1,
  a type bukrs,
  b type waers,
  c type string,
end of test_1.

types:
begin of test_2,
  g type bukrs,
  f type waers,
end of test_2.

data:
lo_struct_descr type ref to cl_abap_structdescr,
ls_test1        type test_1,
ls_test2        type test_2.

ls_test1 = value #( a = '0001' b = 'EUR' c = 'TEST').

lo_struct_descr ?= cl_abap_structdescr=>describe_by_data( p_data =  ls_test1  ).

data(lt_component_test1) = lo_struct_descr->get_components( ).

lo_struct_descr ?= cl_abap_structdescr=>describe_by_data( p_data =  ls_test2  ).

data(lt_component_test2) = lo_struct_descr->get_components( ).

read table lt_component_test2 with key type = lt_component_test1[ name = 'A']-type
  into data(ls_component_a).

read table lt_component_test2 with key type = lt_component_test1[ name = 'B']-type
  into data(ls_component_b).


try.
  data(mapper) =
    cl_abap_corresponding=>create(
      source      = ls_test1
      destination = ls_test2
      mapping     = value cl_abap_corresponding=>mapping_table(
        ( level = 0 kind = 1 srcname = 'A' dstname = ls_component_a-name )
        ( level = 0 kind = 1 srcname = 'B' dstname = ls_component_b-name )
      ) ).

  mapper->execute( exporting source      = ls_test1
                   changing  destination = ls_test2 ).
catch cx_corr_dyn_error into data(exc).
  cl_demo_output=>display( exc->get_text( ) ).
endtry.

如果没有,就使用旧的 assign 语句。

assign component ls_component_a-name of structure ls_test2 to field-symbol(<lv_value>).
<lv_value> = ls_test1-a.

assign component ls_component_b-name of structure ls_test2 to <lv_value>.
<lv_value> = ls_test1-b.