我有两种结构:一种是静态的,一种是动态的。静态结构有四个字段,名称为A B C D.动态结构有两个字段A1和B1,例如,它们与A和B的类型相同,但名称不同。如何将静态结构A和B中的值分配给A1和B2。问题是:如果我的A1和B1被称为A1或A2等,我在运行前不会知道。
感谢您的帮助
答案 0 :(得分:1)
如果您的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.